什么时候这种Kotlin无效安全性有什么问题?

时间:2019-05-07 00:16:15

标签: kotlin

我是科特林学习者的一天。我从https://kotlinlang.org/docs/reference/basic-syntax.html获得了这段代码,然后进行了修改以测试null安全性(https://kotlinlang.org/docs/reference/null-safety.html

每行都有错误。 什么时候以及如何修复此Kotlin null安全性有什么问题?

fun describe(obj?: Any): String =
    when(obj?) {
        1           -> "one"
        "hello"     -> "greeting"
        is Long     -> "long"
        !is String  -> "not String"
        is null     -> "null"
        else        -> "unknown"
    }


fun main() {
    println(describe(1))
    println(describe("Hello"))
    println(describe(1000L))
    println(describe(2))
    println(describe(null))
    println(describe("other"))
}

1 个答案:

答案 0 :(得分:7)

问号表明类型(而不是变量名)可以为空。您还使用了is null,这是错误的,因为null是一个值,而不是类型。这是您所做的更改后的代码,可以编译并运行:

fun describe(obj: Any?): String =
    when(obj) {
        1           -> "one"
        "hello"     -> "greeting"
        is Long     -> "long"
        !is String  -> "not String"
        null        -> "null"
        else        -> "unknown"
    }



fun main() {
    println(describe(1))
    println(describe("Hello"))
    println(describe(1000L))
    println(describe(2))
    println(describe(null))
    println(describe("other"))
}

结果:

one
unknown
long
not String
not String
unknown

似乎您想将null的支票向上移动,因此您的测试将其移到null值为止。照原样,null不是字符串,因此对于null值,您会得到“不是字符串”。