Elvis operator on .toString()

fun main() {
  val nothing = null

  println(nothing.toString() ?: "something")
  println(nothing?.toString() ?: "something")
}

Returns:

null
something

It isn’t something bothering me too much, it’s just strange.
I would expect any null to be handled by elvis oprator.

IntelliJ IDEA does a good job in graying the right side of elvis operator with a warning

“Elvis operator (?:slight_smile: always returns the left operand of non-nullable type String”

(The overload in Library.kt of) toString() is defined as fun Any?.toString(): String. So it will convert any type to a String.

If you add the question mark before toString(), you are telling Kotlin to not invoke it if the value is null. If the value is null, the result of nothing?.toString() will also be null.

So nothing strange is going on here.

In this case it is not returning non-nullable String, but null which should be handled by elvis operator.

It is strange.

Note that nothing.toString() returns "null" which is a String.

Now do you expect "null" ?: "something" to evaluate to "something"?

3 Likes

Oooooh, so it’s not null, its “null”!
That makes sense. Thanks for explaining :slight_smile:

2 Likes