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'm using scala 2.9.1.final
try/catch/finally A basic way we can handle exceptions in Scala is the try/catch/finally construct, really similar to the Java one. In the following example, to make testing easier, we'll return a different negative error code for each exception caught: def tryCatch(a: Int, b: Int): Int = { try { return Calculator.
Throwable is just an alias for java. lang. Throwable . So in Scala, a catch clause that handles Throwable will catch all exceptions (and errors) thrown by the enclosed code, just like in Java.
The Try type represents a computation that may either result in an exception, or return a successfully computed value. It's similar to, but semantically different from the scala. util.
Clearly a compiler bug (the compiler crashes, and REPL tells you That entry seems to have slain the compiler.
). It's not signalling there's anything wrong with your code.
You're creating a single instance of type AnyRef{def toInt(n: Int): Int}
, so creating a singleton object as Kyle suggests might be a better way of going about it. Or create a named class / trait that you insantiate, which works fine.
EDIT: As Luigi Plinge suggested, it's a compiler bug.
Maybe you want something like this...
object x {
def toInt(n:Int) = n * 2
}
scala> x.toInt(2)
res0: Int = 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With