0

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
3
  • The compiler is not able to interfere the type provided for pow2 clearly. If you say val pow2 = pow(_:Double) the example works. Commented Aug 25, 2016 at 8:54
  • What scala version do you use (mine is 2.11.8 REPL) ? Unable to reproduce behavior, val pow2 = pow(_) gets compile error missing parameter type. If I write val pow2: Double => Double = x => pow(x), everything works. Commented Aug 25, 2016 at 8:56
  • sorry you are right, its not a runtime error Commented Aug 25, 2016 at 9:03

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I do not really understand what pow(_) does because pow takes two arguments. Can you comment that?
val pow2 = pow(_) is shorthand for val pow2: Double => Double = x => pow(x), if you write types explicitly.
What @dveim said. Without the type annotation pow(_) you tell the compiler "Here is pow function, I will give you some _ parameter later" but you don't tell it what type it will be. You might give it a conflicting one, say String or a correct one Double. The error is a safeguard against the former case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.