Which would you choose / use? :one: `it.toString(...
# codingconventions
c
Which would you choose / use? 1️⃣
it.toString()
or 2️⃣
"$it"
or 3️⃣ something else? Is 1️⃣ and 2️⃣ equivalent?
1️⃣ 10
👌 2
m
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
The intention with 1 is more obvious. And
toString
in Kotlin is an extension on
Any?
and handles null correctly.
c
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
@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
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.