【问题标题】:How to solve Pattern matching and type erasure in Scala如何在 Scala 中解决模式匹配和类型擦除
【发布时间】:2015-08-18 02:05:51
【问题描述】:

我正在处理现有的一段代码:

def f(s: Option[String]) = …
def matchAny(a: Any) = a match { case s: Option[String] => f(s) }

编译器会警告我(这很正常,因为它不是类型安全的)。

def matchAny(a: Any) = a match { case s: Option[_] => f(s.asInstanceOf[Option[String]] }

我知道它仍然不是类型安全的,但我们收到了警告,并且风险现在明确地出现在代码中。但它更冗长......

那么,您如何看待这种解决方法?还有更好的方法吗?

【问题讨论】:

    标签: scala pattern-matching type-erasure


    【解决方案1】:

    抑制警告的稍微简洁的语法:

    def matchAny(a: Any) = a match { case s: Option[String@unchecked] => f(s) }
    

    在这种情况下(Option[String] 匹配),您还可以使用更安全的版本,如果 String 之外的其他内容在 Option 中,则会立即失败:

    def matchAny(a: Any) = a match { case s@(None | Some(_: String)) => f(s) }
    

    【讨论】:

      【解决方案2】:

      我建议改用 shapeless:

      import shapeless._
      def f(s: Option[String]) = Some("hello world")
      val optionType: TypeCase[Option[String]] = TypeCase[Option[String]]
      def matchAny(a: Any) = a match { case optionType(s) => f(s) }
      

      【讨论】:

        猜你喜欢
        • 2018-01-30
        • 1970-01-01
        • 2018-04-12
        • 2015-10-06
        • 1970-01-01
        • 2016-01-24
        • 2017-11-23
        • 2015-11-21
        • 1970-01-01
        相关资源
        最近更新 更多