What's a idiomatic way to check if an array of strings contains a value in kotlin? Just like ruby's #include?
.
检查字符串数组是否包含kotlin值的惯用方法是什么?就像红宝石的#include一样?
I though about:
我虽然说:
array.filter { it == "value" }.any()
Is there a better way?
有没有更好的办法?
4 个解决方案
#1
14
The equivalent you are looking for is the contains operator.
您正在寻找的等价物是包含运算符。
array.contains("value")
Kotlin offer an alternative infix notation for this operator:
Kotlin为此运营商提供了另一种中缀符号:
"value" in array
It's the same function called behind the scene, but since infix notation isn't found in Java we could say that in
is the most idiomatic way.
这是在场景后面调用的相同函数,但由于在Java中找不到中缀符号,我们可以说in是最惯用的方式。
#2
16
You can use the in
operator which, in this case, calls contains
:
你可以使用in运算符,在这种情况下,调用包含:
"value" in array
数组中的“值”
#3
7
Using in operator is an idiomatic way to do that.
在运算符中使用是一种惯用的方法。
val contains = "a" in arrayOf("a", "b", "c")
#4
2
You could also check if the array contains an object with some specific field to compare with using any()
您还可以检查数组是否包含具有某些特定字段的对象,以便与使用any()进行比较
listOfObjects.any{ object -> object.fieldxyz == value_to_compare_here }
#1
14
The equivalent you are looking for is the contains operator.
您正在寻找的等价物是包含运算符。
array.contains("value")
Kotlin offer an alternative infix notation for this operator:
Kotlin为此运营商提供了另一种中缀符号:
"value" in array
It's the same function called behind the scene, but since infix notation isn't found in Java we could say that in
is the most idiomatic way.
这是在场景后面调用的相同函数,但由于在Java中找不到中缀符号,我们可以说in是最惯用的方式。
#2
16
You can use the in
operator which, in this case, calls contains
:
你可以使用in运算符,在这种情况下,调用包含:
"value" in array
数组中的“值”
#3
7
Using in operator is an idiomatic way to do that.
在运算符中使用是一种惯用的方法。
val contains = "a" in arrayOf("a", "b", "c")
#4
2
You could also check if the array contains an object with some specific field to compare with using any()
您还可以检查数组是否包含具有某些特定字段的对象,以便与使用any()进行比较
listOfObjects.any{ object -> object.fieldxyz == value_to_compare_here }