Hidden features of Scala

Okay, I had to add one more. Every Regex object in Scala has an extractor (see answer from oxbox_lakes above) that gives you access to the match groups. So you can do something like:

// Regex to split a date in the format Y/M/D.
val regex = "(\\d+)/(\\d+)/(\\d+)".r
val regex(year, month, day) = "2010/1/13"

The second line looks confusing if you’re not used to using pattern matching and extractors. Whenever you define a val or var, what comes after the keyword is not simply an identifier but rather a pattern. That’s why this works:

val (a, b, c) = (1, 3.14159, "Hello, world")

The right hand expression creates a Tuple3[Int, Double, String] which can match the pattern (a, b, c).

Most of the time your patterns use extractors that are members of singleton objects. For example, if you write a pattern like

Some(value)

then you’re implicitly calling the extractor Some.unapply.

But you can also use class instances in patterns, and that is what’s happening here. The val regex is an instance of Regex, and when you use it in a pattern, you’re implicitly calling regex.unapplySeq (unapply versus unapplySeq is beyond the scope of this answer), which extracts the match groups into a Seq[String], the elements of which are assigned in order to the variables year, month, and day.

Leave a Comment