-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
--- | ||
layout: post | ||
title: 短路逻辑或/与 | ||
date: 2024-05-11 11:30:00 +0800 | ||
categories: bitwise | ||
tags: bitwise | ||
published: true | ||
--- | ||
|
||
* content | ||
{:toc} | ||
|
||
今天写了如下一段 kotlin 代码: | ||
|
||
```kotlin | ||
fun foo(uid: Int, list: List<Int>): Boolean = list.isEmpty() or ((list.size == 1) and (list[0] == uid)) | ||
``` | ||
|
||
这段代码意图传入一个用户 id 列表和一个用户 id,如果列表为空、或者列表只包含指定的用户 id,则返回 true,否则返回 false。 | ||
|
||
很简单的一段代码,但是在某些场景下崩了。复现和解决也不难,原因是列表为空时,后面的或逻辑会继续执行,导致数组越界异常。<br> | ||
我原本以为 or 和 and 是短路逻辑,看了下源码才发现这两并不是短路的。仔细想想 kotlin 的 or、and 是中缀操作符,其本质上是一个函数,操作符后面的表达式只是该函数的一个参数,自然也就明白为什么不是短路的了。 | ||
|
||
解决方式很简单,换成短路逻辑运算符 `|| &&` 即可: | ||
|
||
```kotlin | ||
fun foo(uid: Int, list: List<Int>): Boolean = list.isEmpty() || (list.size == 1 && list[0] == uid) | ||
``` |