Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception in scala 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'm using scala 2.9.1.final

like image 697
SpiderPig Avatar asked Mar 15 '12 01:03

SpiderPig


People also ask

How do you handle exceptions in Scala?

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.

What is throwable Scala?

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.

What is try in Scala?

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.


2 Answers

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.

like image 70
Luigi Plinge Avatar answered Oct 18 '22 19:10

Luigi Plinge


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
like image 20
Kyle Avatar answered Oct 18 '22 19:10

Kyle