Support relational operators for when

Doing some code I wanted the ability to have a when expression to catch when the value was less than zero. What I wanted was something like:

  when(x)
  {
  < 0 -> throw IllegalArgumentException(“cannot be negative”)
  0 -> 0
  > 0 -> compute(x)
  else -> doSomethingElse()
  }

Which is not supported, but I think it would be a good addition to the pattern matching expressions.

If x was an Int I  could have done:

 &nbsp;&nbsp;in Int.MIN_VALUE..-1 -&gt;

But that is much less readable and notice I had to move from 0 to -1 as my boundary. For a double I would have to make it:

 &nbsp;&nbsp;!in 0..Double.MAX_VALUE -&gt;

But that actually is not equivalent as that will also include the NaN value which before went to the else case

So I think when expressions should support relational operator expressions.

I beleive that this variant is more readable.

when {
  x < 0 -> throw IllegalArgumentException(“cannot be negative”)
  x == 0 -> 0
  x > 0 -> compute(x)
  else -> doSomethingElse()
}


Also, this variant of when expression is too rare.

Except now you are repeating that x over and over. What if x were not a variable, but an expression with side effects? You would then have to introduce a variable in order to repeat its name over and over. By your logic the variant of when that takes an expression should not be part of the language.

I don’t think it is rare at all, occurred for me on very first time using when. People need to do bounds checks all the time. I agree it is less common than in regular Java since you can get ranges for valid array indices but the need to do relational comparions is very common.

I also think it would be nice to have boolean method calls as expressions as in:

  when(myCollection)
  {
  isEmpty() -> handleEmptyCollection()

Perhaps to simplify parsing you might require that to be .isEmpty() to signify that it is a method call.

I know that you want to avoid the complexities of full blown pattern matching like what scala has, but these case seem pretty simple.