News for hackers. Stuff that matters.
Re:Scala – 1 Star – Would Not Program Again by pkinsky on Monday December 02, 2013 @10:28AM (#6834180)
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.

There are no comments on this comment yet.