gpt4 book ai didi

scala - 无法在 Scala 中捕获 ClassCastException

转载 作者:行者123 更新时间:2023-12-04 17:31:53 25 4
gpt4 key购买 nike

我在捕获 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
}

最佳答案

您无法捕获异常,因为您无法转换为 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 添加强制转换以获得正确的返回类型

关于scala - 无法在 Scala 中捕获 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9691990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com