我有一个抽象的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中的最佳实践,并且在计算上更便宜?还有其他方法可以更有效地实现这一想法吗?