2

I recently discovered this nice syntax for a function that only returns a value based on the input:

fun getItem(value: Int): String = when (getPosition(value)) {
   0 -> "Zero"
   1 -> "One"
   2 -> "Two"
   else -> "Other"
}

Is it also possible to use ranges or <> operators?

I've tried doing things like:

>0 -> "Positive"

Which is not accepted, and

0-10 -> "Postively small"

is (naturally) seen as "0 minus 10" I think.

1 Answer 1

5

You can do some of these things, but not in the way you describe. For example you can use is, in and == like this:

val x = 10

when (x) {
    in 0..10 -> 1
    10 -> 2
    is Int -> 3
    else -> 4
}

but you can't use comparison operators (<, >). The reason for this is explained here. You can use arbitrary expressions, but < and > can't be overloaded so you can't do greaterThan(x).

If you are missing some features from Kotlin you can always open a KEEP so at some point, it might get implemented!

Sign up to request clarification or add additional context in comments.

1 Comment

Great! That does the trick; No need for <> in my case, so "between x and u" is perfect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.