Search code examples
kotlinkotlin-null-safety

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


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?

Solution

  • 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.