Scala中的定义顺序重要吗? [英] Order of definition matters in Scala?

查看:73
本文介绍了Scala中的定义顺序重要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当寻找隐式时,Scala编译器会在其他地方查看所涉及类的各个部分的伴随对象。但是,显然,如果在类本身中使用了隐式转换(如果它在同伴对象之前定义),它将无法执行此查找。我能够精通的最小示例是:

When looking for implicits, the Scala compiler looks, among other places, in the companion object of the various parts of the classes involved. Apparently, though, it fails to perform this lookup when the implicit conversion is used in the class itself, if it is defined before the companion object. The minimal example I was able to cook up is:

trait Counter[A] {
  def count(a: A): Int
}

object Foo {
  def foo[A](a: A)(implicit c: Counter[A]) = c.count(a)
}

case class Bar(id: Int) {
  import Foo._

  def count = foo(this)
}

object Bar {
  implicit object BarCounter extends Counter[Bar] {
    def count(b: Bar) = b.id
  }
}

这无法编译,表示找不到参数c的隐式值:Counter [吧] -我正在使用Scala 2.9.1。

This fails to compile saying could not find implicit value for parameter c: Counter[Bar] - I am using Scala 2.9.1.

有趣的事情(由rjsvaljean建议)是,如果我们反转顺序-是,我们在 case class Bar 之前定义 object Bar -非常好的编译。

The interesting thing (suggested by rjsvaljean) is that if we invert the order - that is, we define object Bar before case class Bar - verything compiles fine.


这是编译器错误吗?还是我缺少有关Scala范围规则的信息?

Is this a compiler bug? Or I am missing something about the scope rules of Scala?

我还应该提到,此问题仅在隐式解析时出现。如果我们显式传递 BarCounter 对象,则一切都可以正常编译。

I should also mention that this problem only arises with implicit resolution. If we explicitly pass the BarCounter object, everything compiles fine.

推荐答案

这似乎是一个实际的编译器错误。我已经在此处发布了。

It seems to be an actual compiler bug. I have posted it here.

这篇关于Scala中的定义顺序重要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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