Improved Any?.toString

I love the fact that we have Any?.toString but it returns “null” when the receiver is (duh) null.
Instead of this, we could pass an optional String parameter which could be the return value.

My implementation:

fun Any?.toString(nullReplacement: String = "null"): String {
    if(this == null) return nullReplacement
    return this.toString()
}

How can this be useful? Writing less code for providing the replacement.

Example usage:

Before

return if(foo.bar?.baz == null) "baz is null" else foo.bar?.baz.toString()

After

return foo.bar?.baz.toString("baz is null");

I find the latter one more concise.

This is just as concise:

foo.bar?.baz?.toString() ?: "baz is null"
5 Likes