代码之家  ›  专栏  ›  技术社区  ›  Álvaro Valencia

任何对象的类型转换:模式匹配vs Try()

  •  0
  • Álvaro Valencia  · 技术社区  · 7 年前

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

    1 回复  |  直到 7 年前
        1
  •  2
  •   Brian McCutchon    7 年前

    两个都没有,至少不像你贴的那样。 asInstanceOf 是密码的味道。也, Some() 是不是更喜欢 Option() 代替 正确使用模式匹配:

    def operation(input: Any): Option[Seq[Any]] = {
      input match {
        case s: Seq[Any] => Some(s)
        case _ => None
      }
    }
    

    至于效率 Try 这种方法几乎肯定是最慢的,因为它可能需要计算堆栈跟踪。

    此外,您应该尝试使用比 Any .