I have some problem with catching a ClassCastException.
It happens in last case of the pattern matching of the retrieve function, the exception isn’t cought.
How can I fix this?
abstract class Property
object EmptyProperty extends Property
class PropertyCompanion[T]
object Type extends PropertyCompanion[Type]
case class Type extends Property
object Name extends PropertyCompanion[Name]
case class Name extends Property
abstract class Entity {
protected val properties: Map[PropertyCompanion[_], Property]
def retrieve[T](key: PropertyCompanion[T]) =
properties.get(key) match {
case Some(x) => x match {
case EmptyProperty => throw new Exception("empty property")
case _ => {
try {
x.asInstanceOf[T]
} catch {
case e => throw new Exception("fubar")
}
}
}
case None => throw new Exception("not found")
}
}
case class Book(protected val properties: Map[PropertyCompanion[_], Property]) extends Entity {
def getType = retrieve(Type)
def getName = retrieve(Name)
}
object Test extends App {
val book = Book(Map(Type -> Type(), Name -> Type()))
val name = book.getName
}
You can’t catch the Exception, because you can’t cast to T. The JVM does not know T at runtime, so you have to trick it a bit ;-). Pass in an
implicit m: CLassManifest[T]to your method and usem.erasure.cast(x). Your could would look like this:edit: added a cast to T to get the correct return type