Using Kotlin WHEN clause for comparisons

Even a flexible language such as Kotlin doesn’t have a “elegant” / DRY solution for each and every case.

You can write something like:

when (foo) {
    in 0 .. Int.MAX_VALUE -> doSomethingWhenPositive()
    0    -> doSomethingWhenZero()
    else -> doSomethingWhenNegative()
}

But then you depend on the variable type.

I believe the following form is the most idiomatic in Kotlin:

when {
    foo > 0  -> doSomethingWhenPositive()
    foo == 0 -> doSomethingWhenZero()
    else     -> doSomethingWhenNegative()
}

Yeah… there is some (minimal) code duplication.

Some languages (Ruby?!) tried to provide an uber-elegant form for any case – but there is a tradeoff: the language becomes more complex and more difficult for a programmer to know end-to-end.

My 2 cents…

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)