J  Calbreath
J Calbreath

Reputation: 2705

Scala: restrict parameter values

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.

Upvotes: 4

Views: 1303

Answers (2)

Daenyth
Daenyth

Reputation: 37441

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)

Upvotes: 4

joescii
joescii

Reputation: 6533

The way I would typically approach this in Scala is to make a base trait with case objects:

sealed trait Color
case object Red extends Color
case object Green extends Color
case object Blue extends Color

//...
def myFn(arg:Color) = //...

Upvotes: 3

Related Questions