问题
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