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 this.name or objInstance.name.
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.
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 this.name or objInstance.name.
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val myList = List(1, 2) | |
val res = myList match { | |
case `myList` => "instance itself" | |
case List(_) => "one element" | |
case List(_, _) => "two elements" | |
case _ => "unknown" | |
} | |
println(res) // instance itself |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val myList = List(1, 2) | |
val res = myList match { | |
case List(_) => "one element" | |
case `myList` => "instance itself" | |
case List(_, _) => "two elements" | |
case _ => "unknown" | |
} | |
println(res) // two elements |
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