5 ms·
You can use pattern matching with custom extractors to define partial functions only accepting positive numbers. object Positive { def unapply(x: Int): Optio
by pkinsky 13y ago
You can use pattern matching with custom extractors to define partial functions only accepting positive numbers.
object Positive {
def unapply(x: Int): Option[Int] = if (x>0) Some(x) else None
}
val onlyPositive: PartialFunction[Int, String] = { case Positive(x) => s"check out this positive number: $x" }
This would throw a MatchError for non-positive Ints, but you can also handle the failure case like so:
def onlyPositive(n: Int) = n match {
case Positive(x) => s"check out this positive number: $x"
case _ => s"not a positive number: $n"
}
This is a quick example, but in practice the lack of dependent types is not a huge handicap.