Scala: Pattern matching Cheat Sheet

Use case in function args for pattern matching:

(xs zip ys) map { 
   case (x, y) => x * y 
}

`v42` with backticks is interpreted as the existing val v42, and “Not 42” is printed:

val v42 = 42 
3 match { 
   case `v42` => println("42") 
   case _ => println("Not 42") 
}

UppercaseVal is treated as an existing val, rather than a new pattern variable, because it starts with an uppercase letter. Thus, the value contained within UppercaseVal is checked against 3, and “Not 42” is printed:

val UppercaseVal = 42 
3 match { 
   case UppercaseVal => println("42") 
   case _ => println("Not 42") 
}

Leave a Reply

Your email address will not be published. Required fields are marked *