According to the official kotlin documentation, the toString() call of a null object returns "null" toString()
I want, that toString() should return an empty string ("") instead. I implemented it with an extension function.
fun Any?.toEmptyStringIfNull() :String {
if (this == null) {
return ""
} else {
return toString()
}
I am wondering if this could be achieved simpler/easier/cleaner and without calling the extension function everytime.
How about:
nullable?.toString() ?: ""
or as Alexander Udalov suggested:
nullable?.toString().orEmpty()
Which one can wrap in an extension method:
fun Any?.toStringOrEmpty() = this?.toString() ?: ""
you can directly use nullable.orEmpty()
.
Reference: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/or-empty.html
Edit:
Answer provided is incomplete - does only apply for String?
and not Any?
as pointed out in comment below.
nullable?.let {it.toString()}
If "nullable" is null it won't go further. As a variant. The only problem is that there will be a warning "redundant 'let' call could be removed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With