为什么在 Kotlin 中调用 null 值时 toString 不抛出异常?
Why doesn't toString throw an exception when called on null value in Kotlin?
给定代码
fun main(args: Array<String>) {
val someText: String? = null
println(someText.toString())
}
当运行时,输出为
null
出现两个问题:
- 是否可以实现自定义空安全方法并回退到某些默认代码(比如,我认为 toString 可以)
- 为什么没有抛出异常?
来自docs:
fun Any?.toString(): String
Returns a string representation of the object. Can be called with a null receiver, in which case it returns the string "null".
您可以通过编写 extension function 来实现类似的行为。例如:
fun Any?.foo() = println(this ?: "Sadly, this is null")
fun main(args: Array<String>) {
val x: Int? = null
val y: Int? = 3
x.foo() // "Sadly, this is null"
y.foo() // "3"
null.foo() // "Sadly, this is null"
}
给定代码
fun main(args: Array<String>) {
val someText: String? = null
println(someText.toString())
}
当运行时,输出为
null
出现两个问题:
- 是否可以实现自定义空安全方法并回退到某些默认代码(比如,我认为 toString 可以)
- 为什么没有抛出异常?
来自docs:
fun Any?.toString(): String
Returns a string representation of the object. Can be called with a null receiver, in which case it returns the string "null".
您可以通过编写 extension function 来实现类似的行为。例如:
fun Any?.foo() = println(this ?: "Sadly, this is null")
fun main(args: Array<String>) {
val x: Int? = null
val y: Int? = 3
x.foo() // "Sadly, this is null"
y.foo() // "3"
null.foo() // "Sadly, this is null"
}