13

我认为这是对 Scala 2.10 的新隐式类的正确用法:

implicit case class IntOps(i: Int) extends AnyVal {
  def twice = i * 2
}

11.twice

显然不是:

<console>:13: error: value twice is not a member of Int
              11.twice
                 ^

我错过了什么(Scala 2.10.0-M6)吗?

4

2 回答 2

21

一个线索是隐式类的脱糖,在SIP-13中解释:

implicit class RichInt(n: Int) extends Ordered[Int] {
def min(m: Int): Int = if (n <= m) n else m
...
}

将由编译器转换如下:

class RichInt(n: Int) extends Ordered[Int] {
def min(m: Int): Int = if (n <= m) n else m
...
}
implicit final def RichInt(n: Int): RichInt = new RichInt(n)

如您所见,创建的隐式函数与原始类具有相同的名称。我想这样做是为了让隐式类更容易导入。

因此,在您的情况下,当您创建隐式案例implicit类时,关键字创建的方法名称与关键字创建的伴随对象之间存在冲突case

于 2012-08-13T11:23:30.980 回答
2

这表明存在歧义:

val ops: IntOps = 11

<console>:11: error: ambiguous reference to overloaded definition,
both method IntOps of type (i: Int)IntOps
and  object IntOps of type IntOps.type
match argument types (Int) and expected result type IntOps
       val ops: IntOps = 11
                         ^

不确定到底发生了什么。但是当不使用时case class它似乎很好:

implicit class IntOps(val i: Int) extends AnyVal {
  def twice = i * 2
}

11.twice  // ok
于 2012-08-13T09:42:55.300 回答