定义我自己的toInt方法时scala中的异常

Spi*_*Pig 7 scala exception

为什么这段代码会抛出异常?

val x = new { def toInt(n: Int) = n*2 }
x.toInt(2)
scala.tools.nsc.symtab.Types$TypeError: too many arguments for method toInteger: (x$1: java.lang.Object)java.lang.Integer
        at scala.tools.nsc.typechecker.Contexts$Context.error(Contexts.scala:298)
        at scala.tools.nsc.typechecker.Infer$Inferencer.error(Infer.scala:207)
        at scala.tools.nsc.typechecker.Infer$Inferencer.errorTree(Infer.scala:211)
        at scala.tools.nsc.typechecker.Typers$Typer.tryNamesDefaults$1(Typers.scala:2350)
        ...
Run Code Online (Sandbox Code Playgroud)

我正在使用scala 2.9.1.final

Lui*_*hys 3

显然是编译器错误(编译器崩溃,REPL 告诉你That entry seems to have slain the compiler.)。这并不表明您的代码有任何问题。

您正在创建 type 的单个实例AnyRef{def toInt(n: Int): Int},因此按照凯尔的建议创建单例对象可能是更好的方法。或者创建一个您实例化的命名类/特征,效果很好。