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

use*_*895 1 kotlin

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

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

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"))
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 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"))
}
Run Code Online (Sandbox Code Playgroud)

结果:

one
unknown
long
not String
not String
unknown
Run Code Online (Sandbox Code Playgroud)

看来您想将支票null抬高一点,这样您的测试才能使它变得null物有所值。照原样,null它不是字符串,因此您会获得“非字符串”作为null值。