https://kotlinlang.org logo
Title
c

Chris

06/09/2021, 4:50 PM
Which would you choose / use? 1️⃣
it.toString()
or 2️⃣
"$it"
or 3️⃣ something else? Is 1️⃣ and 2️⃣ equivalent?
:yes: 2
1️⃣ 10
m

Michael Böiers

06/10/2021, 11:38 AM
I hadn’t thought about that before, but what’s so bad about
2
? If it’s really equivalent (no performance penalty), it’s actually more concise.
The alternatives are also not equivalent when it comes to nullability … so 1 should be
it?.toString() ?: "null"
? EDIT: I was wrong, they are equivalent. 🙂
m

mkrussel

06/10/2021, 1:04 PM
The intention with 1 is more obvious. And
toString
in Kotlin is an extension on
Any?
and handles null correctly.
c

Chris

06/10/2021, 1:06 PM
I’ve only started thinking about it because i changed an instance of 1️⃣ to be an instance of 2️⃣ in my project and it introduced a
IllegalFormatConversionException
. I’m still none the wiser as to why because they both produce a String.
m

Michael Böiers

06/10/2021, 4:33 PM
@mkrussel nice! Didn’t know that it returns
"null"
, would have expected
null
. I learn something new about Kotlin every day! 🙂
@Chris That exception usually occurs when you use something like String.format().
c

Chris

06/11/2021, 7:24 AM
Yes, that’s exactly what i was doing. In an android project formatting a string for presenting on the screen. I find it very confusing as to how it was even a problem.