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中,这些选项中哪一个是最佳实践,而且计算成本更低?有没有其他方法可以更有效地实现这个想法?