object Test1 {
def main(args: Array[String]) {
val list = List("a", "b")
list map { x ⇒ println(x) }
list map { case x ⇒ println(x) }
val list2 = List(("aa", "11"))
list2 map {
case (key, value) ⇒ println("key: "+key+", value: "+value)
}
}
}
Please note the last line, why the keyword case
must be used, but the list map { x ⇒ println(x) }
can remove it?
You can't break open the tuple in function literal. That's why you'll have to use case to match them instead. Another way is using tupled to make your function with two arguments fit:
import Function.tupled
list2 map tupled {
(key, value) => println("key: "+key+", value: "+value)
}
{ case (key, value) => f }
is not the same thing as
{ (key, value) => f }
The first is a pattern match that breaks a Tuple2
into its components, assigning their values to key
and value
. In this case, only one parameter is being passed (the tuple). { x => println(x) }
works because x
is assigned the tuple, and println
prints it.
The second is a function which takes two parameters, and makes no pattern matching. Since map
requires a function which takes a single parameter, the second case is incompatible with map
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With