无法在scala中捕获ClassCastException

时间:2012-03-13 20:54:33

标签: scala exception-handling pattern-matching

我在捕获ClassCastException时遇到了一些问题。 它发生在检索函数的模式匹配的最后一种情况下,例外是不正确的。

我该如何解决这个问题?

  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
  }

1 个答案:

答案 0 :(得分:5)

你无法捕获异常,因为你无法转换为T.JVM在运行时不知道T,所以你必须欺骗它一些;-)。将implicit m: CLassManifest[T]传递给您的方法并使用m.erasure.cast(x)。你的看起来像这样:

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
}

编辑:向T添加一个强制转换以获得正确的返回类型