When does Scala need parameter types for anonymous and expanded functions?

后端 未结 2 723
忘了有多久
忘了有多久 2021-02-09 10:04

When does the Scala compiler really need the type information of parameters of anonymous functions?

For instance, given this function:

def callOn[T,R](ta         


        
2条回答
  •  离开以前
    2021-02-09 10:48

    This question has also been answered here:

    Passing functions for all applicable types around

    You expect, ... for Scala's compiler to take into account both parameters to twice to infer the correct types. Scala doesn't do that, though -- it only uses information from one parameter list to the next, but not from one parameter to the next. That mean the parameters f and a [WS: target and f in this case] are analyzed independently, without having the advantage of knowing what the other is.

    Note that it does work with a curried version:

    scala> def callOn[T,R](target: T)(f: (T => R)) = f(target)
    callOn: [T,R](target: T)(f: (T) => R)R
    
    scala> callOn(4)(_.toString)
    res0: java.lang.String = 4
    
    scala> 
    

提交回复
热议问题