bourneli
bourneli

Reputation: 2230

the scala compiler cannot find the correct generic function parameter

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!

Upvotes: 1

Views: 60

Answers (1)

rompetroll
rompetroll

Reputation: 4799

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)) 

Upvotes: 2

Related Questions