Clip number within range in Scala

scala

Solution

I'd write this:

def keepWithinRange(x: Int, min: Int, max: Int) = math.max(min, math.min(max, x))

Or this:

def keepWithinRange(x: Int, min: Int, max: Int) =
  if (x < min) min else if (x > max) max else x

Either is more idiomatic than using `return` for control flow in Scala.

Problem

Give an integer `x`, I'd like to return `x` if it's within the boundaries of some range. If not, return the value of the boundary it violates. ``` def keepWithinRange(x:Int, min:Int, max:Int) : Int = { if (x < min) return min; if (x > max) return max; return x; } ``` Is there a more elegant way to do this?

Original source