1
votes

I see many sources which are titled pattern matching in Scala, but they only discuss match expressions. Is pattern matching in Scala used only in match expressions? Can someone provide a clear understanding of pattern matching versus match expression in Scala?

Should I consider pattern matching a much vaster concept than match expressions? And consider match expression only one of the usages of pattern matching? or in Scala the 2 concepts are thought of as synonyms?

1
Can you elaborate on what you mean by match expression which doesn't refer to pattern matching?Yuval Itzchakov

1 Answers

1
votes

match expressions are just one way to use pattern matching. The same concepts are used in a variety of context,such as:

//Exception handling    
try{
   //....
} catch {
   case ex: NullPointerException => ex.printStackTrace()
   case Exception(msg) => println(msg)
   case _ => println("error")
}

and

// Map/flatMap/filter for collections
val l  = List(1, "2", 3L, Some(1L))
l.foreach { 
 case l:Long => println("Long 1")
 case s:String => println(s)
 case Some(n) => println(n)
 case None => println("error")
 case _ => println("dunno")
}