While playing around in Scala, I came up against something that I think should be possible, but I don’t know how to do.
I’m returning a value that’s bounded by a given min/max. With an if-else statement, the function would look like this:
def set(n: Int, min: Int, max: Int): Int =
{
if (n < min) return min
if (n > max) return max
return n
}
I was wondering if it was possible to do this (elegantly) with pattern matching. I tried the following, but it was syntactically incorrect:
def set(n: Int, min: Int, max: Int): Int = n match
{
case (n < min) => min
case (n > max) => max
case _ => n
}
I think there’s a way to do it by mixing case and if statements, but by the time I’ve done that I might as well just be using a standard if/else chain. Is there a correct syntax to do what I’m attempting?
Pattern matching works but is less elegant:
because:
(or if you like line breaks:
)
Return not needed.
(Don’t forget
math.min(max,math.max(min,n)), either.)