我正在努力实现这样的目标:
def a(b: Any) = { b match { case x: Seq[String] => println("x") } } // somewhere else a(List("b"))结果我喜欢看到“x”被打印,而我却不喜欢。
基本上我想匹配一个类型/特征,并覆盖其类型派生自/实现此类型/特征的所有对象,特征是Seq,并且类型参数是事先已知的。 因为我是scala新手,所以我很困惑。
想法?
I'm trying to achieve something like this:
def a(b: Any) = { b match { case x: Seq[String] => println("x") } } // somewhere else a(List("b"))As a result I'd love to see "x" being printed, and I don't.
Basically I want to match against a type/trait and cover all of the objects whose types derive from/implement such type/trait, with the trait being Seq and the type parameter being known in advance. Since I'm a scala novice I'm quite stuck, however.
Ideas?
最满意答案
由于类型擦除,您无法检查参数化类型。 看到这个问题,为什么会出现警告: 有关此Scala模式匹配中未经检查的类型参数的警告?
另一个问题及其答案告诉你如何解决这个问题: 如何解决Scala上的类型擦除问题? 或者,为什么我无法获取我的集合的类型参数?
然而,当您不检查类型参数时,您的代码工作正常:
scala> List("a") match { case _: Seq[_] => 1 case _ => 2 } res0: Int = 1You can't check against parameterized types because of type erasure. See this question why there will be a warning: Warning about an unchecked type argument in this Scala pattern match?
Another question and its answers tell you how to get around that: How do I get around type erasure on Scala? Or, why can't I get the type parameter of my collections?
Nevertheless your code works fine, when you don't check against type parameters:
scala> List("a") match { case _: Seq[_] => 1 case _ => 2 } res0: Int = 1更多推荐
发布评论