3

Can someone explain why nums.map(+2) does not work but nums.map(2+) works?

scala> val nums=List(1,2,3,4)
nums: List[Int] = List(1, 2, 3, 4)

scala>  nums.map(2+)
res3: List[Int] = List(3, 4, 5, 6)

scala> nums.map(+2)
<console>:27: error: type mismatch;
 found   : Int(2)
 required: Int => ?
       nums.map(+2)
                ^
Soumya
  • 31
  • 2

1 Answers1

6

Look at the signature for map():

final def map[B](f: (A) => B): List[B]

The argument, f, is a function from A to B. 2+ fulfills that function requirement because it is a syntactic shorthand for 2.+(_). In other words, the +() method invoked on an instance of the Int class, turned into a proper function via eta expansion.

If you want the + before the 2 then you can .map(_+2).

jwvh
  • 50,871
  • 7
  • 38
  • 64