为什么这个几乎相同的值 class 不起作用?

Why doesn't this almost-identical value class work?

正如在 http://docs.scala-lang.org/overviews/core/value-classes.html 承诺的那样,这有效:

class Wrapper(val self: Int) extends AnyVal {
  def toHexString: String = java.lang.Integer.toHexString(self)
}
println(12.toHexString)

但这不能编译:

class Wrapper(val self: Int) extends AnyVal {
  def whyNot:      String = java.lang.Integer.toHexString(self)
}
println(12.whyNot)

为什么不呢?我唯一改变的是方法的名称!

错误信息如下:

error: value whyNot is not a member of Int
    println(12.whyNot)
               ^

是的,我仔细检查了 whyNot 中的 schtupit Unicode 字符。

我不确定你为什么认为它应该编译。

整数没有 whyNot 方法。 Wrapper 有一个 whyNot 方法,但是 12 是一个 Int,而不是 Wrapper

您需要在 Wrapper 对象上调用 whyNot

new Wrapper(12).whyNot
// => "c"

Predef.scala defines Int 到 RichInt 的隐式转换:

  @inline implicit def intWrapper(x: Int)         = new runtime.RichInt(x)

当您调用 println(12.toHexString) 时,它不会查看您的 Wrapper,它会隐式转换为 RichInt 并使用 defined there.

方法

如果你想要自己的隐式转换,你需要使用 implicit keyword:

来定义它
implicit class Wrapper(val self: Int) extends AnyVal {
  def whyNot:      String = java.lang.Integer.toHexString(self)
}
println(12.whyNot)  // prints "c"