/**
* 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?
Christopher Mederos
06/26/2024, 5:04 AM
or does it make more sense to just do something like ...
Copy code
myOptional?.toString() ?: ""
☝️ 1
s
Szymon Jeziorski
06/26/2024, 5:53 AM
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
Christopher Mederos
06/26/2024, 6:27 AM
ok nice, thanks for the tip
c
CLOVIS
06/26/2024, 7:23 AM
You could create your own
Copy code
fun Any?.toStringOrEmpty() =
this?.toString().orEmpty()