字符串模板中的Nullable var

时间:2015-11-20 09:31:40

标签: nullable kotlin

Kotlin有一项名为string templates的功能。在字符串中使用可空变量是否安全?

var ShoppingCartBig = React.createClass({
componentDidMount: function () {

    ShoppingCartStore.dispatcher.subscribe(function (o) {
        this.setState({ shoppingCart: o.data });
    });
},

如果override fun onMessageReceived(messageEvent: MessageEvent?) { Log.v(TAG, "onMessageReceived: $messageEvent") } NullPointerException,上述代码会抛出messageEvent吗?

1 个答案:

答案 0 :(得分:5)

你总是可以在try.kotlinlang.org上制作一个小项目,亲眼看看:

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

fun test(a: String?) {
    print("result: $a")
}

此代码编译正常并打印null。为什么会这样?我们可以查看extension functions上的文档,它说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()
}

所以,基本上,它首先检查它的参数是否为null,如果不是,则调用该对象的成员函数。