K Zhang K Zhang - 10 months ago 38
Scala Question

What is the difference of the three variable of Scala's map function

The following three

map
function call on a Scala
List
all produced the same result.

Can someone tell me what is the actual different on them?

val l = List(1,2,3,4,5,6,7,8)

l.map(x => x * 2)
l.map{x => x * 2}
l.map{case x => x * 2}

Answer Source

The case thingy is actually syntax for PartialFunction. You can have more than one clause like that:

 l.map { 
   case 1 => "one"
   case 2 => "two"
   case _ => "foo"
 }

This actually passes a PartialFunction to map, not just a Function, but that works, because PartialFunction is a subclass of Function. The resulting PartialFunction is defined on those parameters, that are matched by a case clause, and not on others:

l.collect { 
   case 1 => "one"
   case 2 => "two"
}

Returns List("one", "two")

You can also use case to deconstruct tuples or case classes (or anything else that has unapply or unapplySeq), like pointed out in the other answer, same way you would in a match expression.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download