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...


We can use let to achieve this behaviour.

response.code().let {
    when {
        it == 200 -> handleSuccess()
        it == 401 -> handleUnauthorisedError()
        it >= 500 -> handleInternalServerError()
        else -> handleOtherErrors()
    }
}

Hope this helps

Tags:

Kotlin