Raphael Roth Raphael Roth - 3 months ago 11
Scala Question

Use method with default parameter in map

I want to map a stream of

Doubles
to a method which takes two parameters, one of them has a default value. I want to use the default parameter so my method has only 1 parameter which I need to pass:

def pow(x:Double, exponent:Double=2.0) = {
math.pow(x,exponent)
}


I've found out that the following works, but I do not understand why:

val res = (1 to 100).map(_.toDouble).map(pow(_))


I'm especially confused because the following does not work (compiler error because of missing type information):

val pow2 = pow(_)
val res = pow2(2.0)
println(res) // expect 4.0

Answer

The compiler is not able to infer the type that you will provide to pow2. In the res mapping you explicitly feed it a collection of Doublesand therefore pow(_) does not complain. However, in the case of val pow2 = pow(_) it complains that type parameter is missing. Change it to

val pow2 = pow(_: Double)
val res = pow2(2.0)
println(res)

and it will work just fine. pow(_) will be expanded two x => pow(x) and at this point the compiler cannot infere what's x without the type annotation.