Pattern-matching anonymous functions


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")
    }
Last updated: 2024-04-14 05:09:31scala
Author:Chaolocation:https://www.baidu.com/article/28
Comments
Submit
Be the first one to write a comment ~