Monday, 25 June 2012

Scala: constant in pattern matching or always do a Unit testing!

Every Scala coder should remember the difference between Constant and Variable patterns in
pattern matching. Short refresh from this topic: if pattern starts from low case letter: it is counted as a variable. We can still use a lowercase name for a pattern constant, using one of two tricks:
1). If the constant is a field of any object, we can prefix it with a qualifier. For example, name is a variable pattern, but or

2) Second workaround is enclosing the variable name with back ticks. For instance, `name` would again be interpreted as a constant, not as a variable.

Here an example for constant, constructor, sequence and default matching cases, using the List:
And funny situation when it doesn't work (looks like it is fixed in betas of 2.10):

Just few line of code with simple behaviour (depends on standart library and language construction only). Of course don't trust Scala isn't the outcome, just always do a Unit testing.

No comments:

Post a Comment