```/** * Returns a string representation of the o...
# getting-started
c
Copy code
/**
 * Returns a string representation of the object. Can be called with a null receiver, in which case
 * it returns the string "null".
 */
public fun Any?.toString(): String
Is there a version of Any?.toString() that would return an empty string instead of the "null" when called with a null neceiver?
or does it make more sense to just do something like ...
Copy code
myOptional?.toString() ?: ""
☝️ 1
s
IMO it makes more sense to be explicit about your intention and either use elvis operator with the fallback case as you wrote, or utilize
String?.orEmpty()
extension, which would result in exactly the same. Example:
myOptional?.toString().orEmpty()
👍 1
c
ok nice, thanks for the tip
c
You could create your own
Copy code
fun Any?.toStringOrEmpty() =
    this?.toString().orEmpty()
👍 1
k
Also, be careful of places where
toString()
is called implicitly, such as
println(x)
.
1