2012-03-15 68 views
7

为什么此代码会抛出异常?在定义我自己的toInt方法时scala中的异常

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) 
     ... 

我使用Scala的2.9.1.final

+0

由于这是一个编译器错误,我建议通过在[Scala的问题跟踪器](https://issues.scala-lang.org/secure/Dashboard.jspa)中提交错误报告来更好地制作Scala。 – leedm777 2012-03-15 18:30:09

+0

不会在2.10中继上崩溃。 – soc 2012-03-16 00:22:59

回答

3

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

您正在创建类型为AnyRef{def toInt(n: Int): Int}的单个实例,因此按照Kyle的建议创建单例对象可能是更好的方法。或者创建一个你命名的class/trait,它工作正常。

2

编辑:作为路易吉Plinge建议,这是一个编译器错误。

也许你想这样的事情...

object x { 
    def toInt(n:Int) = n * 2 
} 

scala> x.toInt(2) 
res0: Int = 4 
+0

“scalas toInt”是什么意思? new {}没有可以覆盖的toInt方法。只有我定义的toInt方法。 – SpiderPig 2012-03-15 02:27:36