the scala compiler cannot find the correct generic function parameter -
i have scala code 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 used simple getfun2. think use "x = _.sum", scala compiler can find correct type, seems failed.
can body explain reason of error.
thanks!
getfun
uses type variables whereas getfun2
uses explicit types.
so, getfun2
, compiler knows calling sum
function on array[int]
. knows how sum integers, things work.
for getfun
compiler knows there array of something (t
stands some type). not how sum something, have compiler here , tell t
is. 1 possibility did in first line, specifying array type in function lambda. pass along type parameter values this:
println(getfun[int,double](_.sum, arr))
Comments
Post a Comment