Is there a way to restrict the values of a parameter in a Scala function? For example, if I have one paramater called flag and I only want the user to be able to submit the values 0 or 1 as valid values for that parameter.
I know I could write a simple if statement that checked the values and returned an error message of some sort if it isn't acceptable, but I thought there might be a more succinct way to do it, say when the parameter is named in the function declaration.
What you want is "dependent typing". This sort of call would be a compile error in a language with support for it. Unfortunately scala doesn't support it.
Two typical workarounds would be to use an ADT instead of the larger type, or a wrapper with a restricted method of construction.
object ZeroOrOne {
def apply(i: Int): Option[ZeroOrOne] = if (i == 0 || i == 1) Some(ZeroOrOne(i)) else None
}
case class ZeroOrOne private (i: Int)
def doStuff(zo: ZeroOrOne) { // use zo.i }
or
sealed trait EnableStatus
case object Enabled extends EnableStatus
case object Disabled extends EnableStatus
def setEnabled(es: EnableStatus)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With