基类上的模式匹配和Scala中的所有派生类(Pattern matching on base class and all derived classes in Scala)

编程入门 行业动态 更新时间:2024-10-25 16:28:25
基类上的模式匹配和Scala中的所有派生类(Pattern matching on base class and all derived classes in Scala)

我正在努力实现这样的目标:

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 = 1

You 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

更多推荐

本文发布于:2023-04-27 22:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329061.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模式   派生类   Pattern   基类上   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!