Scala视图应用程序难题

说我们有以下两个特点:

trait Foo[A] { def howMany(xs: List[A]) = xs.size }
trait Bar

并从第二个到第一个隐含的转换:

implicit def bar2foo[A](bar: Bar) = new Foo[A] {}

我们创建一个Bar和一个整数列表:

val bar = new Bar {}
val stuff = List(1,2,3)

现在我期待以下工作:

bar howMany stuff

但它没有:

scala> bar howMany stuff
<console>:13: error: type mismatch;
 found   : List[Int]
 required: List[A]
              bar howMany stuff
                          ^

所以我们去the spec,这就是说(粗体重点是我的):

Views are applied in three situations.

  1. [Isn’t relevant here.]

  2. In a selection e.m with e of type T,if the selector m does not denote a member of T. In this case,a view v is searched which
    is applicable to e and whose result contains a member named m. The
    search proceeds as in the case of implicit parameters,where the
    implicit scope is the one of T. If such a view is found,the
    selection e.m is converted to v(e).m.

  3. In a selection e.m(args) with e of type T,if the selector m denotes some member(s) of T,but none of these members is applicable to the arguments args. In this case a view v is searched
    which is applicable to e and whose result contains a method m
    which is applicable to args. The search proceeds as in the case of
    implicit parameters,where the implicit scope is the one of T. If
    such a view is found,the selection e.m is converted to
    v(e).m(args).

所以我们尝试以下,认为工作太荒谬了,

trait Foo[A] { def howMany(xs: List[A]) = xs.size }
trait Bar { def howMany = throw new Exception("I don't do anything!") }

implicit def bar2foo[A](bar: Bar) = new Foo[A] {}

val bar = new Bar {}
val stuff = List(1,3)

但是(至少在2.9.2和2.10.0-RC2上):

scala> bar howMany stuff
res0: Int = 3

这导致了一些非常奇怪的行为,例如this workaroundthis problem.

我有三个(密切相关)的问题:

>有没有一个直截了当的方式(即不涉及添加具有适当名称的假方法)的方式,以便在上述原始情况下正确应用视图?
有人可以提供说明这个行为的规范吗?
假设这是预期的行为,它有什么意义吗?

我也很感激与以前讨论这个问题的任何链接 – 我对Google没有太多的好运气.

解决方法

为了大家的参考,这只能是一个错误.你知道的方式是错误信息:

<console>:13: error: type mismatch;
 found   : List[Int]
 required: List[A]

列表[A]不是一个真正的类型 – 它是列表应用于其自己的类型参数.这不是一种可以要求的类型,因为它不是可以表达的类型.

[编辑 – 太早了,谁知道我在说什么.忽略上面的内容,但您仍然可以按照链接.]

相关门票为https://issues.scala-lang.org/browse/SI-6472.

相关文章

共收录Twitter的14款开源软件,第1页Twitter的Emoji表情 Tw...
Java和Scala中关于==的区别Java:==比较两个变量本身的值,即...
本篇内容主要讲解“Scala怎么使用”,感兴趣的朋友不妨来看看...
这篇文章主要介绍“Scala是一种什么语言”,在日常操作中,相...
这篇文章主要介绍“Scala Trait怎么使用”,在日常操作中,相...
这篇文章主要介绍“Scala类型检查与模式匹配怎么使用”,在日...