We had interesting discussion about `Any?.toString...
# stdlib
e
We had interesting discussion about
Any?.toString()
method. Are there original thoughts why it is there? Except of logging, are there other use cases? Especially
println(null)
and
println(null.toString())
are looking same in console.
j
I think you got it backwrads 🙂
println(x)
calls
x.toString()
to know what to print, so without
Any?.toString()
you would only have
println(String)
and you would need to explicitly convert things to strings before you can print or interpolate them
s
I've seen
Any?.toString()
cause many bugs, I'd rather it not exist
👍 1
j
I guess it would have been nice to have a
Stringable
or
Printable
interface, instead of giving this function to
Any?
(or rather
Object
, because it definitely comes from Java)
1
e
Kotlin 3.x? 🙂
j
This is a Java thing. I don't think it can ever realistically change. Millions of things depend on this function being present on all objects
😢 1
e
println()
is Kotlin funcion
s
The important distinction is for
null.toString()
. In Java it's a runtime error; in Kotlin it's `"null"`—which is the bit that I object to, since it causes bugs and surprises
👍🏼 1
thank you color 1
👍 1
So @Joffrey I think your point holds true for
toString()
in general, but not necessarily for the nullable overload that Kotlin adds on top
j
to follow other patterns in the stdlib
it should be toStringOrNull()
j
> The important distinction is for null.toString(). In Java it's a runtime error; in Kotlin it's "null"—which is the bit that I object to, since it causes bugs and surprises Ah! Ok I missed the point, then I agree. Yeah I have something against extensions on nullable types in general, actually. I just don't like the idea that
x.something()
may be safe on nullable stuff - it doesn't look/feel right.
So yeah it would be great not to have the overload with nullable receiver to avoid such problems. But honestly, that too might be too much of a breaking change. Feel free to open an issue for it and see what the Kotlin team thinks about it, though
e
I find
List<*>?.orEmpty()
quite useful
j
I don't know, I don't like those. I feel like the regular
.
syntax hides the fact that it's nullable when skimming through the code, and I find it confusing. I much prefer
?: emptyList()
in most cases
🙌🏼 1
🙌 1
o
The
.orEmpty
and more generally
.orDefault(X)
has become a standard Kotlin convention IMO. Maybe when Kotlin was new it could have "hidden the fact that it's nullable", but now it's standard naming. Similar to
toList
(creates a new list) vs
asList
(wraps, does not allocate a new list)
j
I guess it's just a question of habit, which I didn't get 🙂 I'm 100% with you on
toX()
vs
asX()
, though
r
It’s way too late now but I wish you couldn’t interpolate a nullable reference into a string template. I’ve made that mistake a few times.
2