字符串模板中的可空变量
Nullable var inside string template
Kotlin 有一个叫做 string templates 的特性。在字符串中使用可空变量是否安全?
override fun onMessageReceived(messageEvent: MessageEvent?) {
Log.v(TAG, "onMessageReceived: $messageEvent")
}
如果 messageEvent
是 null
,上面的代码会抛出 NullPointerException
吗?
你总是可以在 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
,如果不是,则调用该对象的成员函数。
Kotlin 有一个叫做 string templates 的特性。在字符串中使用可空变量是否安全?
override fun onMessageReceived(messageEvent: MessageEvent?) {
Log.v(TAG, "onMessageReceived: $messageEvent")
}
如果 messageEvent
是 null
,上面的代码会抛出 NullPointerException
吗?
你总是可以在 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
,如果不是,则调用该对象的成员函数。