简体   繁体   中英

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 :

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

I would recommend use shapeless instead:

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) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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