Nullable var inside string template

こ雲淡風輕ζ 提交于 2020-06-23 07:05:12

问题


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")
}

Will the above code throw NullPointerException if messageEvent is null?


回答1:


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")
}

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()
}

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



来源:https://stackoverflow.com/questions/33823223/nullable-var-inside-string-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!