Home > Back-end >  Scala - Using anonymous function shorthand for successive map() calls
Scala - Using anonymous function shorthand for successive map() calls

Time:02-19

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.

CodePudding user response:

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.

  • Related