gpt4 book ai didi

Kotlin: "if item not in list"正确的语法

转载 作者:IT老高 更新时间:2023-10-28 13:28:41 28 4
gpt4 key购买 nike

鉴于 Kotlin 的列表查找语法,

if (x in myList)

相对于惯用的 Java,

if (myList.contains(x))

如何表达否定?编译器不喜欢这些:

if (x not in mylist)

if !(x in mylist)

除了 if !(mylist.contains(x))) 之外,还有其他惯用的表达方式吗?我没有看到 Kotlin Control Flow docs. 中提到它

最佳答案

使用 x !in list 语法。

以下代码:

val arr = intArrayOf(1,2,3)
if (2 !in arr)
println("in list")

被编译成等价于:

int[] arr = new int[]{1, 2, 3};
// uses xor since JVM treats booleans as int
if(ArraysKt.contains(arr, 2) ^ true) {
System.out.println("in list");
}

in!in 运算符使用任何名为 contains 的可访问方法或扩展方法并返回 Boolean。对于集合 (list, set...) ,它使用 collection.contains 方法。对于数组(包括原始数组),它使用扩展方法 Array.contains 实现为 indexOf(element) >= 0

关于Kotlin: "if item not in list"正确的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43664110/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com