Scala has a built-in general pattern matching mechanism. It allows to match on any sort of data with a first-match policy.The
match
keyword provides a convenient way of applying a function (like the pattern matching function above) to an object.- The first case has two '_' wildcards, they will match any values of the first two parameters of Person.
- 'a' refers to 'p.age'. This case will success when if condition holds.
- The second case will success when the first case fails and p.lastname = 'Neward'
- The third case is also called 'extractor', which makes the values of 'p' be used in the local variables of the case.
- The last case will execute, when all above cases fail.
- case class Person(first: String, last: String, age: Int) {
- println(first);
- println(last)
- println(age)
- }
- def process(p: Person) =
- {
- "Processing " + p + " reveals that" +
- (p match {
- case Person(_, _, a) if a > 30 =>
- " they're certainly old."
- case Person(_, "Neward", _) =>
- " they come from good genes...."
- case Person(first, last, ageInYears) if ageInYears > 17 =>
- first + " " + last + " is " + ageInYears + " years old."
- case _ =>
- " I have no idea what to do with this person"</span>
- })
- }
- def matArray(a: List[Any]) {
- a match {
- case 0 :: Nil => { print("an array contains 0 as an element") }
- case x :: y :: Nil => { print("an array contains only two elements") }
- case 0 :: tail => { print("an array with head as 0") }
- case _ =>print("default")
- }
- }
No comments:
Post a Comment