I started learning Scala yesterday, so I'm pretty new to it. One thing I like to do when learning a new language is trying to create a micro-TDD lib.
This is what I got so far:
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] )
}
The code for assert
works just fine, but I'm having two problems with assertThrows
.
- It seems that I can't use
E
on the last line. No matter what I do, I get aclass type expected but E found error
. - If I remove E from the last line (replacing it by
throw new AssertionError("error expected")
, for example) I get this:warning: abstract type E in type pattern is unchecked since it is eliminated by erasure
I think that the two problems I'm having are related with the way Scala (and probably java) deals with abstract types, and how are they done.
How can I fix my assertThrows?
Bonus points: is the way I'm specifying a "block type" (f: => Unit
) correct ?