scala anonymous function missing parameter type error

后端 未结 2 2029
鱼传尺愫
鱼传尺愫 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:30

    It seems to me that because "f" is in the same parameter list as "xs", you're required to give some information regarding the type of x so that the compiler can solve it.

    In your case, this will work:

    mapFun(List(1,2,3) , (x: Int) => x * x)  
    

    Do you see how I'm informing the compiler that x is an Int?

    A "trick" that you can do is currying f. If you don't know what currying is check this out: http://www.codecommit.com/blog/scala/function-currying-in-scala

    You will end up with a mapFun like this:

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

    And this will work:

    mapFun(List(1,2,3))(x => x * x)
    

    In the last call, the type of x is resolved when the compiler checks the first parameter list.

    EDIT:

    As Dominic pointed out, you could tell the compiler what your types are. Leading to:

    mapFun[Int, Int](List(1,2,3), x => x * x)
    

    Cheers!

提交回复
热议问题