字符串模板中的Nullable var

naX*_*aXa 1 nullable kotlin

Kotlin有一个名为字符串模板的功能.在字符串中使用可空变量是否安全?

override fun onMessageReceived(messageEvent: MessageEvent?) {
    Log.v(TAG, "onMessageReceived: $messageEvent")
}
Run Code Online (Sandbox Code Playgroud)

将上面的代码抛出NullPointerException,如果messageEventnull

aga*_*aga 6

您可以随时在try.kotlinlang.org上创建一个小项目,亲眼看看:

fun main(args: Array<String>) {
    test(null)
}

fun test(a: String?) {
    print("result: $a")
}
Run Code Online (Sandbox Code Playgroud)

此代码编译精细和打印null.为什么会这样?我们可以查看有关扩展函数的文档,它说这个toString()方法(将在你的messageEvent参数上调用String它来实现它)被声明如下:

fun Any?.toString(): String {
    if (this == null) return "null"
    // after the null check, 'this' is autocast to a non-null type, so the toString() below
    // resolves to the member function of the Any class
    return toString()
}
Run Code Online (Sandbox Code Playgroud)

所以,基本上,它检查它的参数是否是null第一个,如果不是,则调用该对象的成员函数.