scala anonymous function missing parameter type error

后端 未结 2 2105
鱼传尺愫
鱼传尺愫 2020-12-30 23:26

I wrote the following

def mapFun[T, U](xs: List[T], f: T => U): List[U] = (xs foldRight List[U]())( f(_)::_ )

and when I did

<         


        
2条回答
  •  星月不相逢
    2020-12-30 23:37

    The limitation of scala's type system that you're running into here is that the type information flows from left to right across parameter groups and does not flow from left to right within a parameter group.

    What this means is that specifying the type parameter T by providing a List[Int] will not provide that information to other parameters within the group like f. Which results in a missing parameter type error. But it will provide it to f if f were a part of the next parameter group. This is why the curried function approach works.

    i.e. if you defined it like this:

    def mapFun[T, U](xs: List[T])(f: T => U): List[U] = (xs foldRight List[U]())( f(_)::_ )
    

    The type parameter T that you define in the first parameter group: (xs: List[T]) as Int will be made available to the next parameter group: (f: T => U). So now you do not have to explicitly specify T at the call site.

提交回复
热议问题