1

I have scala code as following

object Main extends App {
   def getFun[T, U](x: Array[T] => U, p: Array[T]): U = { x(p) }
   def getFun2(x: Array[Int] => Double, p: Array[Int]): Double = { x(p) }

   val arr = Array(1, 2, 3, 4)
   println(getFun((x: Array[Int]) => x.sum, arr))
   // println(getFun(_.sum, arr))  // error, why!
   // println(getFun(x = _.sum, arr))  // error, why!
   println(getFun2(_.sum.toDouble, p = arr))
}

Why getFun cannot be used as simple as getFun2. I think use the "x = _.sum", the scala compiler can find the correct type, but it seems that it failed.

Can any body explain the reason of the error.
Thanks!

1 Answer 1

2

getFun uses type variables whereas getFun2 uses explicit types.

So, for getFun2, the compiler knows that it is calling the sum function on an Array[Int]. It knows how to sum up Integers, things work.

For getFun the compiler only knows that there is an array of something (T stands for some type). It does not how to sum up something, we have to help the compiler here and tell it what T is. One possibility is what you did in the first line, specifying the array type in the function lambda. Another would be to pass along type parameter values like this:

println(getFun[Int,Double](_.sum, arr)) 
Sign up to request clarification or add additional context in comments.

Comments

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.