The One Thing I Hate About Kotlin - Make Helsinki

The One Thing I Hate About Kotlin

by: Davor Skontra
  •   Mobiilisovellukset •  18.3.2018   •  2 minuutin lukuaika

== true

I love Kotlin. It’s an amazing language. I wrote it a love letter once.
But… There is one thing about it that sucks.

Petter Griffin saying null is not true, null is not false.

Null is not true.
Null is not false.

For example, this fails to compile

if (nullableBoolean) {

If you want to get that to work you need to compare it to true.

if (nullableBoolean == true) {

Then you submit that for a PR and with a bit of luck a team member with not much experience with the language picks it up.

Naturally they immediately assume you are an idiot.

“Hey dude, you probably shouldn’t be comparing stuff to boolean literals.”
“Yea I know. It’s a language feature. Believe me..”

I mean sure, you could use the elvis operator like this to avoid looking stupid

if (nullableBoolean ?: false)  {


But it’s ugly and less readable. On top of that, the linter will complain that you should use == true instead.

What makes this problem worse is that if you expect something to be false, this won’t work.

if (nullableBoolean == false) {


Since null is not false you would have a bug here. So you end up with

if (nullableBoolean != true) {



Unfunny rage comic character.


There is however a solution to this that comes to mind.

val <T: Boolean?> T.truthy
   get() = this ?: false

Here we extend nullable booleans with a truthy property which would return false if the value is null. Then you could write

if (nullableBoolean.truthy) {


This looks good, until you try to to do this

if (nullableObject?.nullableBoolean.truthy) {


Since the nullableObject could return null before truthy is evaluated, this won’t compile.

 An alternative is to make it a function instead of an extension

fun truthy(nullableBool: Boolean?): Boolean = nullableBool == true

Which is sort of OK, but may be less readable than a simple == true.

 What do you guys think?

Leave a Reply

Your email address will not be published.