Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable var inside string template

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?

like image 953
naXa Avatar asked Nov 20 '15 09:11

naXa


1 Answers

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.

like image 133
aga Avatar answered Sep 30 '22 16:09

aga