Practical Use Cases of Switch Statement in Scala
November 27, 2019 Leave a comment
1. Catch blocks are Pattern Matches and is same as below code
try {
// logic
} catch {
case e: RuntimeException => "runtime"
case e: NullPointerException => "npe"
case _ => "something else"
}
// Catch blocks are Pattern Matches and is same as below code
/*
try {
// logic
} catch(e) {
e match {
case e: RuntimeException => "runtime"
case e: NullPointerException => "npe"
case _ => "something else"
}
}
*/
2. Generators are also based on pattern matching
val list = List(1, 2, 3, 4)
val evenOnes = for {
x <- list if x % 2 == 0 // GENERATOR
} yield x
println(evenOnes)
val tuples = List((1, 2), (2, 3))
val filterTuples = for {
(first, second) <- tuples // extractor in this generator
} yield first * second
println(filterTuples)
3. Multi value definitons are based on PMs
val tuple = (1, 2, 3)
val (a, b, c) = tuple
println(b)
val head :: tail = list
println(head)
println(tail)
4. Partial Functions are based on Pattern Matching
val mappedList = list.map {
case v if v % 2 == 0 => s"$v is even"
case 1 => "One"
case _ => "Something else "
}
println(mappedList)
// Note: Partial Function is a literal inside {}
// is same as
val mappedList2 = list.map(x => x match {
case v if v % 2 == 0 => s"$v is even"
case 1 => "One"
case _ => "Something else "
})
Recent Comments