Method taking implicit CanBuildFrom does not work with eta-expansion?

前端 未结 2 1082
一向
一向 2021-01-13 04:07

I have a following method:

def firstAndLast[CC, A, That](seq: CC)(implicit asSeq: CC => Seq[A], cbf: CanBuildFrom[CC, A, That]): That = {
  val b = cbf(se         


        
相关标签:
2条回答
  • 2021-01-13 04:19

    Though they look similar, these are different things:

    List("abc", "def") map {firstAndLast(_)}
    // { x => firstAndLast(x) }
    
    List("abc", "def") map firstAndLast
    // firstAndLast, if it happened to be a function
    

    Now, note how the compiler can easily type x in the first case. In the second case, it is trying to figure out how (seq: CC)(implicit asSeq: CC => Seq[A], cbf: CanBuildFrom[CC, A, That]) might be interpreted as Function1[String, ???], and it is failing because there's a lot of information missing -- namely, the type parameters.

    In other words, in the first case, the compiler first types x, and, therefore, CC, and then tries to figure out the rest. In the second case, the compiler is trying to figure out all of the type parameters at the same time.

    0 讨论(0)
  • 2021-01-13 04:23

    Not a full answer to your question, but I’ve just noticed that this works:

    List("abc", "def") map firstAndLast[String, Char, String]
    

    It then means that the type inferencer is having trouble determining the right type parameters for firstAndLast, but I wouldn’t know how to fix it…

    0 讨论(0)
提交回复
热议问题