Skip to content

Instantly share code, notes, and snippets.

@npryce
Created September 18, 2016 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npryce/e62036ab9b75538d5c5352d48727e191 to your computer and use it in GitHub Desktop.
Save npryce/e62036ab9b75538d5c5352d48727e191 to your computer and use it in GitHub Desktop.
A Kotlin pitfall w.r.t. nulls and toString
val x : SomeType? = ... // Note: nullable

val s1 : String? = x?.toString()

val s2 : String? = x.toString()

The expressions s1 and s2 are subtly different. When x is null, s1 will evaluate to null, while s2 will evaluate to the string "null".

This is because the Kotling standard library defines toString on Any?, with a special case for null to return the string "null".

Resulting bugs are very difficult to track down. Hopefully your tests will catch your mistake, but the error message will be something like

Assertion failed:
expected: null
actual:   null

If you get failures like this, look for a missing or unwanted question mark. It'll be hard to spot, but hopefully this tip will save you a few hours of frustration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment