作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 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
当前的情况。
有没有人有任何见解?对于 5
,第一个分支确实是 true
。
最佳答案
当您传递参数时,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"
}
关于kotlin - "Pattern match"不适用于 Int 子句(分支),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37755789/
我是一名优秀的程序员,十分优秀!