I have some code that routinely does type checks like that:
obj match {
case _: Foo =>
// everything is fine
case _ =>
throw SomeException(...)
}
It works, but this is relatively bulky and feels like tons of duplicated code (especially given that exception requires lots of parameters), so I thought it would replace this an assertion function. However, my naïve try failed:
def assertType[T](obj: CommonType): Unit = {
obj match {
case _: T =>
// everything is fine
case _ =>
throw SomeException(...)
}
}
Obviously, due to JVM type erasure, this T
parameter is ignored, so first case branch is always true. ⇒ Full source code demonstrating the problem
Of course, one can resort to Java's reflection methods, but that's slow, ugly, and unportable. What is the preferred way to do such assertions in Scala?
Somewhat related, but do not address this exact issue: