我在Kotlin(我开始学习)中有这段代码:
package io.shido.learning
import java.time.Instant
fun typeCheck(any: Any): Any = when (any) {
(any is Int && any < 10) -> "(small) integer"
is Int -> "integer"
is Double -> "double"
is String -> "string"
else -> "another Any"
}
fun main(args: Array<String>) {
println("type check for: 5 (${typeCheck(5)})")
println("type check for: 20 (${typeCheck(20)})")
println("type check for: 56.0 (${typeCheck(56.0)})")
println("type check for: \"a string\" (${typeCheck("a string")})")
println("type check for: Instant (${typeCheck(Instant.now())})")
}
...所以我希望typeCheck(5)
返回(small) integer
而不是integer
。
有没有人有任何见解?第一个分支true
确实是5
。
答案 0 :(得分:7)
传递参数时,when
检查参数是否与分支中的值匹配,而5与第一个分支中的计算true
不匹配。所以基本上你可以这样修复你的代码:
fun typeCheck(any: Any): Any = when {
(any is Int && any < 10) -> "(small) integer"
any is Int -> "integer"
any is Double -> "double"
any is String -> "string"
else -> "another Any"
}
或
fun typeCheck(any: Any): Any = when (any) {
in 0..10 -> "(small) integer"
is Int -> "integer"
is Double -> "double"
is String -> "string"
else -> "another Any"
}