1

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?
Wojciech Wirzbicki
  • 3,887
  • 6
  • 36
  • 59

1 Answers1

2

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.

Community
  • 1
  • 1
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680