Ho iniziato ad imparare Scala ieri, quindi sono abbastanza nuovo. Una cosa che mi piace fare quando apprendo una nuova lingua è cercare di creare una lib di micro-TDD.Scala - Come si esegue un metodo "assertThrows"?
Questo è quello che ho ottenuto finora:
def assert(condition: Boolean, message: String) {
if(!condition){ throw new AssertionError(message) }
}
def assertThrows[E](f: => Unit) {
try {
f
} catch {
case e: E => { return }
case _: Exception => { }
}
throw new AssertionError("Expected error of type " + classOf[E])
}
Il codice per assert
funziona bene, ma sto avendo problemi con due assertThrows
.
- Sembra che non sia possibile utilizzare
E
sull'ultima riga. Non importa quello che faccio, ottengo unclass type expected but E found error
. - Se rimuovo E dall'ultima riga (sostituendolo con
throw new AssertionError("error expected")
, per esempio) ottengo questo:warning: abstract type E in type pattern is unchecked since it is eliminated by erasure
Penso che i due problemi che sto avendo sono correlati con il modo in Scala (e, probabilmente, java) si occupa di tipi astratti e di come sono fatti.
Come posso risolvere il mio assertThrows?
Punti bonus: è il modo in cui sto specificando un "tipo di blocco" (f: => Unit
) corretto?
Una domanda che non avevo molto tempo fa potrebbe essere di aiuto: http://stackoverflow.com/questions/7699709/scala-expected-exception-snippet –