在 Kotlin 中是否有更好的替代表达方式: a == b || a == c
我正在寻找类似a == b || c
或a.equals(b, c)
for*_*pas 11
我认为最简单的方法是使用in
运算符:
a in listOf(b, c)
Run Code Online (Sandbox Code Playgroud)
您可以在列表中包含任意数量的项目。
您可以when
用作
when(a){
b,c -> println("match") // match either b or c
else -> println("no match") // in case of no match
}
Run Code Online (Sandbox Code Playgroud)
此外,您可以使用in
范围如
when(number){
100,200 -> println(" 100 or 200 ")
in 1..5 -> println("in range") // between 1 - 5
!in 6..10 -> println("not in range") // not between 6 - 10
else -> println("no match")
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用多个自定义enum
值作为
// often used to represent API/process status etc
when(Status.ERROR){
in listOf(Status.ERROR, Status.EXCEPTION) -> println("Something when wrong")
else -> println("Success")
}
enum class Status{
SUCCESS, ERROR, EXCEPTION
}
Run Code Online (Sandbox Code Playgroud)
另一个选择(我个人更喜欢)是创建一个扩展函数:
fun Any.equalsAny(vararg values: Any): Boolean {
return this in values
}
Run Code Online (Sandbox Code Playgroud)
使用示例:
val result1 = 20.equalsAny(10, 20, 30) // Returns true
val result2 = "ABC".equalsAny(10, 20, 30, 99 , 178) // Returns false
val result3 = "ABC".equalsAny("ABC", "XYD", "123") // Returns true
val result4 = "ABC".equalsAny("xxx", "XYD", "123") // Returns false
Run Code Online (Sandbox Code Playgroud)
你甚至可以混合类型并且它可以完美地工作:
val a = 1
val b = "10"
val c = true
val search = 999
val search2 = false
val result5 = search.equalsAny(a, b, c) // Returns false
val result6 = search2.equalsAny(a, b, c, 872, false) // Returns true
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
792 次 |
最近记录: |