Romain Guy @romainguy.dev · Nov 27

I love Kotlin but please don't abuse its features. I regularly see code like in the first function when you can instead write a simple if statement: it's shorter, easier to read, and doesn't allocate an object! Thankfully both functions compile to the same assembly when R8 is turned on.

141 likes 11 replies

?

Replies

Gijs L · Nov 28

And with badly named extension functions. With *Arrow* it can go both ways too.

George · Nov 27

I recently turned down a PR for this reason. My theory is that people feel "smart" when using arcane symbols such as "?:" and "?.".

Romain Guy · Nov 27

Note that even when R8 is on, the first function will be more expensive in interpreted mode. It's only after compilation to aarch64 by ART that it becomes fully optimized. If you don't have R8 on, well… ART still does wonders on the final code mind you (no branches, and a single call).

Chris Krueger · Nov 28

@romainguy.dev Does the first example allocate objects? It uses inline modifier which means the function will be inlined at the call site.

Chris Krueger · Nov 27

I also prefer the second more readable example. Especially new developers without Java experience use the first one a lot.

Tom Colvin · Nov 27

It's insane that the compiler produces the same for both of those. Practically magic

Bekir Khan · Nov 28

Damn that looks ugly, would look 10x better in scala tbh

Savvas · Nov 27

Agree but with a caveat. Kotlin needs a ternary operation. It's the only syntax I envy from other langs. "if-else" seems verbose to me given how succinct the rest of the language is. This was discussed ages ago and turned down (discuss.kotlinlang.org/t/ternary-op...) but I still want it damn it! 😂

manpreet · Nov 27

You are gonna love what I have done here tinyurl.com/36sahzay

P-Y · Nov 27

My own pet peeve is when folks use `?.let {} ?:` instead of if/else when checking null It's less readable, and more error prone (because if "doThing()" accidentally returns null, then you end up running the ?: branch, which often is not what you actually want.

Stylianos Gakis · Nov 27

The one time I sometimes cave in and use .let for is for compose delegated mutableState which can not be safecast to not-null in a normal if check.