Given the code
fun main(args: Array<String>) {
val someText: String? = null
println(someText.toString())
}
When run, output is
null
Two questions appear:
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"
}