采用隐式 CanBuildFrom 的方法不适用于 eta-expansion? [英] Method taking implicit CanBuildFrom does not work with eta-expansion?

查看:38
本文介绍了采用隐式 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
}

请参阅:采用 Seq[T] 返回 String 而不是 Seq[Char] 的方法以了解基本原理.在第一种情况下它就像一个魅力,但在第二种情况下无法编译:

See: Method taking Seq[T] to return String rather than Seq[Char] for rationale. It works like a charm in the first case but fails to compile in the second:

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 是问题(?)

Any idea how to improve this declaration to avoid extra wrapping? Seems like eta-expansion is the problem (?)

推荐答案

虽然它们看起来很相似,但它们是不同的:

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

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

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.

换句话说,在第一种情况下,编译器first类型x,因此,CC,然后尝试计算剩下的.在第二种情况下,编译器试图同时找出所有类型参数.

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.

这篇关于采用隐式 CanBuildFrom 的方法不适用于 eta-expansion?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆