【发布时间】:2019-02-18 23:29:01
【问题描述】:
我有一个抽象的 Scala 类,它的方法接收一个类型为Any 的值。根据扩展它的类,此值的预期类型会有所不同。
让我们看一个使用模式匹配的例子:
abstract class A {
def operation(input: Any): Any
}
class B extends A {
// In this class, the input parameter is expected to be a Seq[Any]
def operation(input: Any): Any = {
input match {
case _: Seq[Any] => Option(input.asInstanceOf[Seq[Any]]))
case _ => None
}
}
}
class C extends A {
// In this class, the input parameter is expected to be a Map[String, Any]
def operation(input: Any): Any = {
input match {
case _: Map[String, Any] => Option(input.asInstanceOf[Map[String, Any]]))
case _ => None
}
}
}
这是使用Try()函数的实现:
class B extends A {
// In this class, the input parameter is expected to be a Seq[Any]
def operation(input: Any): Any = {
Try(input.asInstanceOf[Seq[Any]]).toOption
}
}
class C extends A {
// In this class, the input parameter is expected to be a Map[String, Any]
def operation(input: Any): Any = {
Try(input.asInstanceOf[Map[String, Any]]).toOption
}
}
哪些选项可以成为 Scala 中的最佳实践,并且计算成本更低?有没有其他方法可以更有效地实现这个想法?
【问题讨论】:
标签: scala casting type-conversion pattern-matching try-catch