我试图比较Triples而忽略了某些值Triple.我希望在下面忽略的价值表示为_.请注意,下面的代码是出于示例目的而不编译,因为它_是一个Unresolved reference.
val coordinates = Triple(3, 2, 5)
when (coordinates) {
Triple(0, 0, 0) -> println("Origin")
Triple(_, 0, 0)-> println("On the x-axis.")
Triple(0, _, 0)-> println("On the y-axis.")
Triple(0, 0, _)-> println("On the z-axis.")
else-> println("Somewhere in space")
}
Run Code Online (Sandbox Code Playgroud)
我知道你可以_在解构时使用,如果你想忽略一个值,但这似乎没有帮助我解决上述问题:
val (x4, y4, _) = coordinates
println(x4)
println(y4)
Run Code Online (Sandbox Code Playgroud)
我有什么想法可以达到这个目的吗?
谢谢!
未使用的变量的下划线在Kotlin 1.1中引入,它被设计为在解构声明中不需要某些变量时使用.
在表达式的分支条件中,Triple(0, 0, 0)正在创建新实例但不是解构.因此,此处不允许使用下划线.
目前,在Kotlin中无法表达的分支条件下进行解构.您的案例的解决方案之一是在每个分支条件中详细比较每个组件:
val (x, y, z) = Triple(3, 2, 5)
when {
x == 0 && y == 0 && z == 0 -> println("Origin")
y == 0 && z == 0 -> println("On the x-axis.")
x == 0 && z == 0 -> println("On the y-axis.")
x == 0 && y == 0 -> println("On the z-axis.")
else -> println("Somewhere in space")
}
Run Code Online (Sandbox Code Playgroud)
这是关于表达时的解构的讨论.
| 归档时间: |
|
| 查看次数: |
93 次 |
| 最近记录: |