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

kotlin
kotlin null pointer exception
kotlin if null else
kotlin return null
kotlin double exclamation mark
optional kotlin
kotlin let else
nullable string kotlin

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() ?: ""

Safe calls(?.) vs Null checks(!!) in Kotlin · Suneet Agrawal, system, the compiler can detect possible NullPointerException errors at compile time and reduce the possibility of having them thrown at runtime. Kotlin’s requireNotNull() vs Not Null Assertion !! Kotlin provides two methods to call nullable type objects — requireNotNull() and !! operator. Both throws an exception if the object is null.

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.

what does "::" mean in kotlin?, There are a few ways of doing that. Checking for null in conditions. First, you can explicitly check if b is null, and handle the two options separately  Kotlin introduces a new and secure way to deal with nulls. In kotlin, you cannot directly assign ‘ null ’ to any variable or object. In kotlin no variable, by default, can be set to null. For

I propose an extension function stringify, the name of which I borrowed from JavaScript's JSON.stringify().

fun <T> T?.stringify(toString: (T) -> String = { it.toString() }): String =
    if (this == null) "" else toString(this)

This covers the simple case and cases where you want to further process the string:

fun simplyConcatenate(s: String, postfix: String?): String = 
    s + postfix.stringify()

fun getFullTitle(title: String, disambiguation: String?): String = 
    title + disambiguation.stringify { " ($it)" }

fun demo() {
    println(simplyConcatenate("a", null)) // "a"
    println(simplyConcatenate("a", "b")) // "ab"
    println(getFullTitle("a", null)) // "a"
    println(getFullTitle("a", "b")) // "a (b)"
}

Nullable Types and Null Safety in Kotlin, Kotlin by default forces to initialize every object with a value and that should not be null. However, we can make a nullable type object, by explicitly informing Kotlin that the object can be null. Sometimes you can get null on non-nullable object. If you work with Java classes (for example some library) and if the Java method which you call is annotated with @Nullable it might return null. Kotlin compiler will not detect it, and you will get a NullPointerException on runtime.

Null Safety, With the introduction of null safety in Kotlin, everybody now know this the best solution in some case (even though they could achieve what's  data?.let { // execute this block if not null } ?: run { // execute this block if null } But this seems not to be quite as readable as a simple if-else statement. Also, you might find this Q&A useful: In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them

Null Safety Tutorial in Kotlin: Best Practices, In Kotlin, the type system distinguishes between references that can hold null (​nullable but before figuring out the difference among both, let's understand what they are in detail first. Another way of using a nullable property is safe call operator ? and will return it if it's not null else will evaluate the right side expression. In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them 12 Whats the best way in kotlin for an null object's toString() method to return an empty string instead of “null”

The different ways to handle Nullable type in Kotlin, GBlog · Puzzles · What's New? Kotlin compiler also throws NullPointerException if it found any null reference without executing The most common way of checking null reference is using if-else expression. In other words, if left expression is not null then elvis operator returns it, otherwise it returns the right expression. Kotlin's type system is aimed at eliminating the danger of null references from code, also known as the The Billion Dollar Mistake. One of the most common pitfalls in many programming languages, including Java, is that accessing a member of a null reference will result in a null reference exception. In Java this would be the equivalent of a NullPointerException or NPE for short.

Comments
  • Or a slightly more readable version: nullable?.toString().orEmpty()
  • The implementation could probably be "${this ?: ""}", if you don't care about less performance
  • This is the better answer.
  • orEmpty takes a String object, and the question is about converting Any? to String.
  • @javaxian, thanks for pointing out. You are indeed correct. Will update my answer.