Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this `case` is a must needed?

Tags:

case

scala

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?

like image 385
Freewind Avatar asked Nov 27 '22 07:11

Freewind


2 Answers

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)
}
like image 134
thoredge Avatar answered Dec 16 '22 21:12

thoredge


{ 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.

like image 22
Daniel C. Sobral Avatar answered Dec 16 '22 22:12

Daniel C. Sobral