Why doesn't toString throw an exception when called on null value in Kotlin? [duplicate]

独自空忆成欢 提交于 2019-12-02 07:37:12

问题


Given the code

fun main(args: Array<String>) {
    val someText: String? = null
    println(someText.toString())
}

When run, output is

null

Two questions appear:

  • is that possible to implement custom null-safe method with fallback to some default code (like, I think, toString does)
  • why no exception is thrown?

回答1:


From the 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".

You can achieve similar behaviour by writing an extension function. For example:

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

Live example.



来源:https://stackoverflow.com/questions/49237928/why-doesnt-tostring-throw-an-exception-when-called-on-null-value-in-kotlin

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