Could not catch ClassCastException in scala
I have a problem catching the ClassCastException. This happens in the latter case of pattern matching of the extract function, no exception is thrown.
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
}
+3
source to share
1 answer
You cannot catch the Exception because you cannot use T. The JVM does not know T at runtime, so you have to trick it a bit ;-). Go implicit m: CLassManifest[T]
to your method and use m.erasure.cast(x)
. Yours might look like 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])(implicit m: ClassManifest[T]) =
properties.get(key) match {
case Some(x) => x match {
case EmptyProperty => throw new Exception("empty property")
case _ => {
try {
m.erasure.cast(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
}
edit: added listing to T to get the correct return type
+5
source to share