trait Foo[A] { def howMany(xs: List[A]) = xs.size } trait Bar
并从第二个到第一个隐含的转换:
implicit def bar2foo[A](bar: Bar) = new Foo[A] {}
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.
[Isn’t relevant here.]
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.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 workaround的this problem.
我有三个(密切相关)的问题:
>有没有一个直截了当的方式(即不涉及添加具有适当名称的假方法)的方式,以便在上述原始情况下正确应用视图?
有人可以提供说明这个行为的规范吗?
假设这是预期的行为,它有什么意义吗?
我也很感激与以前讨论这个问题的任何链接 – 我对Google没有太多的好运气.