Daniel Tan
Daniel Tan

Reputation: 181

Scala - Using anonymous function shorthand for successive map() calls

So this works

@ val arr = Array(1.1,2.2,3.3)
arr: Array[Double] = Array(1.1, 2.2, 3.3)

@ val mean = arr.sum / arr.length
mean: Double = 2.1999999999999997

@ arr.map(_ - mean).map(x => x + x)
res3: Array[Double] = Array(-2.1999999999999993, 8.881784197001252E-16, 2.2)

But this doesn't

@ arr.map(_ - mean).map(_ + _)
cmd4.sc:1: missing parameter type for expanded function ((<x$2: error>, x$3) => x$2.$plus(x$3))
val res4 = arr.map(_ - mean).map(_ + _)
                                 ^
cmd4.sc:1: missing parameter type for expanded function ((<x$2: error>, <x$3: error>) => x$2.$plus(x$3))
val res4 = arr.map(_ - mean).map(_ + _)
                                     ^
Compilation Failed

And I'd really like to understand why.

Upvotes: 2

Views: 78

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70267

Every _ in a lambda is a different argument, so this

.map(_ + _)

actually means

.map((x, y) => x + y)

which is an error since map expects a single-argument function.

Upvotes: 2

Related Questions