Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the best way in kotlin for an null object's toString() method to return an empty string instead of "null"

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.

like image 763
Lukas Lechner Avatar asked Apr 22 '16 13:04

Lukas Lechner


3 Answers

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() ?: ""
like image 151
miensol Avatar answered Oct 17 '22 04:10

miensol


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.

like image 42
Hartmut Avatar answered Oct 17 '22 02:10

Hartmut


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.

like image 1
Sergey Domashchuk Avatar answered Oct 17 '22 02:10

Sergey Domashchuk