如何在 Kotlin 中正确使用时控制数据流



有人可以向我解释为什么这段代码块打印这些行吗通常,我们使用 when 来控制数据流,使用多种可能性,例如 is !is in !in 这是我的代码:

fun isNumber(obj: Any) {
    when (obj) {
        !is Long, Int, Float, Double -> {
            println("No it's not a number")
        }
        else -> {
            println("Yes it's a number")
        }
    }
}
fun main(args: Array<String>) {
    isNumber(19.10)
    isNumber(19L)
    isNumber(19)
    isNumber(19.10F)
}

结果 :

No it's not a number
Yes it's a number
No it's not a number
No it's not a number

逗号分隔的条件用 OR 来计算,每个条件都有自己的条件,所以我们应该像这样扭转它:

    when (obj) {
        is Long, is Int, is Float, is Double -> {
            println("Yes it's a number")
        }
        else -> {
            println("No it's not a number")
        }
    }

您的构造不起作用的原因是,当您省略!is Long, Int, Float, Double ->中的is时,我们有(简化):

   when (obj) {
            Int -> {
            }
            else -> {
            }
        }

这意味着你检查obj是否等于类Int,而不是检查obj是否是Int的实例。

此外,即使我们将!is添加到每种数字类型,例如:

   when (obj) {
        !is Long, !is Int, !is Float, !is Double -> {
            println("No it's not a number")
        }
        else -> {
            println("Yes it's a number")
        }
    }

它仍然不起作用,因为如前所述,条件将用 OR 进行评估,所以一切都"不是数字",因为所有东西要么不是,要么不是 Int 等。

最新更新