2012-03-15 10 views
7

Dlaczego ten kod rzuca wyjątek?Wyjątek w scali podczas definiowania własnej metody INN

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

Używam Scala 2.9.1.final

+0

Ponieważ jest to błąd kompilatora, polecam dokonywania Scala lepiej składając raport o błędzie w [problem tracker Scala] (https://issues.scala-lang.org/secure/Dashboard.jspa). – leedm777

+0

Nie ulega awarii w 2,1 trunk. – soc

Odpowiedz

3

Wyraźnie błędów kompilatora (kompilator wywala i REPL informuje That entry seems to have slain the compiler.). To nie jest sygnał, że coś jest nie tak z twoim kodem.

Tworzysz pojedyncze wystąpienie typu AnyRef{def toInt(n: Int): Int}, więc tworzenie pojedynczego obiektu, jak sugeruje Kyle, może być lepszym sposobem na obejście tego problemu. Lub utwórz nazwaną klasę/cechę, którą insantiate, która działa dobrze.

2

EDIT: Jak sugeruje Luigi Plinge, jest to błąd kompilatora.

Może chcesz coś takiego ...

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

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

Co masz na myśli przez "scalas toInt"? new {} nie ma metody toInt, którą mógłbym przesłonić. Jest tylko zdefiniowana przeze mnie metoda toInt. – SpiderPig

Powiązane problemy