Hello ! Why is it useful that toString can return ...
# stdlib
j
Hello ! Why is it useful that toString can return a “null” string if it is applied to null? I may sound silly to you, but I didn’t know. As a result, I just passed some time looking for why
val a = b?.c.toString()
where
b == null
results
a != null
since in this case
a == "null"
. So to get what I want, I have to write
val a = b?.c?.toString()
. It’s not a problem, I just don’t understand the purpose.
😐 3
d
It may be to emulate the behavior in Java when concatenation includes a null object.
m
I find it very convenient e.g in debug logs
👍 2
b
If I read you code correctly, it is not that toString() returns a null but that b?.<anything> returns a null. You said that b==null, so b?. will always return null. Try to make b!=null then if c is also not null, a should be a string IF toString() was defined to not return null.
e
What was the code you were writing doing? What were you using toString for?
j
In an Android application, I receive an entity from an API that has a potential link with another entity. So an optional UUID field. I store my entity with room and I convert my UUID into a string if it exists. Otherwise the field remains null.
🙏 1