Scala exception when defining my own toInt method

Why does this code throw an 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) ... 

I am using scala 2.9.1.final

+7
source share
2 answers

Clearly, a compiler error (the compiler fails, and the REPL reports That entry seems to have slain the compiler. ). This does not indicate something is wrong with your code.

You create one instance of type AnyRef{def toInt(n: Int): Int} , so creating a singleton object, as Kyle suggests, may be the best way to get around it. Or create a named class / trait that you are pursuing that works great.

+3
source

EDIT: As Luigi Plinge suggested, this is a compiler error.

Maybe you want something like this ...

 object x { def toInt(n:Int) = n * 2 } scala> x.toInt(2) res0: Int = 4 
+2
source

All Articles