字符串模板中的可空var [英] Nullable var inside string template

查看:65
本文介绍了字符串模板中的可空var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Kotlin has a feature called string templates. Is it safe to use nullable variables inside a string?

override fun onMessageReceived(messageEvent: MessageEvent?) {
    Log.v(TAG, "onMessageReceived: $messageEvent")
}

如果messageEventnull,上面的代码是否会抛出NullPointerException?

Will the above code throw NullPointerException if messageEvent is null?

推荐答案

您总是可以在try.kotlinlang.org上创建一个小项目,然后亲自看看:

You can always make a tiny project on try.kotlinlang.org and see for yourself:

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

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

此代码可以正常编译并打印null.为什么会这样?我们可以查看扩展功能上的文档,其中说toString()方法(其中将会在您的messageEvent参数上调用,以使其中的String声明如下:

This code compiles fine and prints null. Why this happens? We can check out the documentation on extension functions, it says that toString() method (which will be called on your messageEvent parameter to make String out of it) is declared like so:

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,如果不是,则调用此对象的成员函数.

So, basically, it checks if its argument is null first, and, if it isn't, invokes member function of this object.

这篇关于字符串模板中的可空var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆