scala – 采用隐式CanBuildFrom的方法不适用于eta-expansion?

我有以下方法:

def firstAndLast[CC, A, That](seq: CC)(implicit asSeq: CC => Seq[A], cbf: CanBuildFrom[CC, A, That]): That = {
  val b = cbf(seq)
  b += seq.head
  b += seq.last
  b.result
}

参见:Method taking Seq[T] to return String rather than Seq[Char]的理由.它在第一种情况下就像一个魅力,但在第二种情况下无法编译:

List("abc", "def") map {firstAndLast(_)}
List("abc", "def") map firstAndLast

赠送:

error: No implicit view available from CC => Seq[A].
List("abc", "def") map firstAndLast

知道如何改进此声明以避免额外包装?似乎eta-expansion是问题(?)

最佳答案 虽然看起来很相似,但这些是不同的东西:

List("abc", "def") map {firstAndLast(_)}
// { x => firstAndLast(x) }

List("abc", "def") map firstAndLast
// firstAndLast, if it happened to be a function

现在,请注意编译器在第一种情况下如何轻松键入x.在第二种情况下,它试图弄清楚如何(seq:CC)(隐含asSeq:CC => Seq [A],cbf:CanBuildFrom [CC,A,那])可能被解释为Function1 [String ,?它是失败的,因为缺少很多信息 – 即类型参数.

换句话说,在第一种情况下,编译器首先键入x,然后键入CC,然后尝试找出其余部分.在第二种情况下,编译器试图同时找出所有类型参数.

点赞