简体   繁体   English

如何在Scala中解决模式匹配和类型擦除

[英]How to solve Pattern matching and type erasure in Scala

I'm working on an existing piece of code : 我正在处理现有的代码:

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

And the compiler warns me (it's normal because it's not typesafe). 并且编译器警告我(这是正常的,因为它不是类型安全的)。

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

I know it's still not typesafe, but we gain the warning and the risk appears now explicitly in the code. 我知道它仍然不是类型安全的,但是我们得到了警告,并且该风险现在已明确显示在代码中。 But it's more verbose… 但这更冗长...

So, what do you think about this workaround ? 那么,您如何看待这种解决方法? And is there a better way ? 还有更好的方法吗?

Slightly less verbose syntax that suppresses warning: 略显冗长的语法可以抑制警告:

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

In this case ( Option[String] matching), you can also have safer version which will fail immediately if something else than String is in the Option : 在这种情况下( Option[String]匹配),您还可以拥有更安全的版本,如果Option String不是String则该版本将立即失败:

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

I would recommend use shapeless instead: 我建议改用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) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM