In scala match
is used on pattern match, which matches different cases of value:
val x: Any = "hello"
x match {
case s: String => println(s"$s is a String")
case i: Int => println(s"$i is an Int")
case _ => println("Unknown type")
}
You can convert a match
statement to a pattern-matching anonymous function. A pattern-matching anonymous function is a function, whose parameter is a case statement of a pattern-match. Example:
val f: Any => Unit = {
case s: String => println(s"$s is a String")
case i: Int => println(s"$i is an Int")
case _ => println("Unknown type")
}
In this example, f
is an anonymous function of a pattern match that takes a case statement as its parameter. You could use this anonymous function to handle different values, just like you would use a match statement.
f("hello") // "hello is a String"
f(42) // "42 is an Int"
f(3.14) // "Unknown type"
When use flatmap/map, we could also use a pattern-matching anonymouse function.
original
.flatMap(value=>value match{
case s: String => println(s"$s is a String")
case i: Int => println(s"$i is an Int")
})
Using a pattern-matching anonymouse
.flatMap({
case s: String => println(s"$s is a String")
case i: Int => println(s"$i is an Int")
})
We could also use {} in scala, so we could write it like this:
.flatMap{{
case s: String => println(s"$s is a String")
case i: Int => println(s"$i is an Int")
}}
We could make it more simpler version by stripping the duplicated{}
.flatMap{
case s: String => println(s"$s is a String")
case i: Int => println(s"$i is an Int")
}