English 中文(简体)
CanBuildFrom 的隐含方法与 eta-Expanation 无效吗?
原标题:Method taking implicit CanBuildFrom does not work with 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
}

给 :

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

如何改进这个声明以避免额外的包装? 问题似乎就在于“ eta- expanation ” (? )

最佳回答

尽管它们看起来相似,但这些都是不同的东西:

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

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

现在,请注意编纂者如何在第一个案例中容易地键入 < code> x 。 在第二个案例中,它试图找出 < code> (seq: CC) (隐含为Seq: CC {gt; Seq[ A], cbf: CanBuild From[CC, A, that]) 可以被解释为 < code> Function1[String,???] ? , 并且由于缺少大量信息 -- -- 即类型参数 -- 而失败了。

换句话说,在第一种情况下,汇编者 first type ,因此, CC ,然后试图找出其余的。在第二种情况下,汇编者试图同时找出所有类型参数。

问题回答

但我刚刚注意到这有效:

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

意思是, 型号推论者很难为 < code> first and Last 确定正确的类型参数, 但我不知道如何修正它...





相关问题
How to flatten a List of different types in Scala?

I have 4 elements:List[List[Object]] (Objects are different in each element) that I want to zip so that I can have a List[List[obj1],List[obj2],List[obj3],List[obj4]] I tried to zip them and I ...

To use or not to use Scala for new Java projects? [closed]

I m impressed with Twitter and investigating to use Scala for a new large scale web project with Hibernate and Wicket. What do you think about Scala, and should I use it instead of Java? EDIT: And, ...

Why does Scala create a ~/tmp directory when I run a script?

When I execute a Scala script from the command line, a directory named "tmp" is created in my home directory. It is always empty, so I simply deleted it without any apparent problem. Of course, when I ...

Include jar file in Scala interpreter

Is it possible to include a jar file run running the Scala interpreter? My code is working when I compile from scalac: scalac script.scala -classpath *.jar But I would like to be able to include a ...

Scala and tail recursion

There are various answers on Stack Overflow which explain the conditions under which tail recursion is possible in Scala. I understand the limitations and how and where I can take advantage of tail ...

热门标签