What are the hidden features of Scala that every Scala developer should be aware of?
One hidden feature per answer, please.
hidden-featuresscala
What are the hidden features of Scala that every Scala developer should be aware of?
One hidden feature per answer, please.
Best Answer
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:The second line looks confusing if you're not used to using pattern matching and extractors. Whenever you define a
val
orvar
, what comes after the keyword is not simply an identifier but rather a pattern. That's why this works: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
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 callingregex.unapplySeq
(unapply
versusunapplySeq
is beyond the scope of this answer), which extracts the match groups into aSeq[String]
, the elements of which are assigned in order to the variables year, month, and day.