Skip to content

Commit

Permalink
feat: short circuit bitwise(or/and)
Browse files Browse the repository at this point in the history
  • Loading branch information
y4n9b0 committed May 11, 2024
1 parent dc2a36e commit 2aadbb6
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions _posts/2024-05-11-short-circuit-bitwise.md
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)
```

0 comments on commit 2aadbb6

Please sign in to comment.