在Scala列表中的某处匹配对象

在Scala列表中的某处匹配对象,scala,pattern-matching,Scala,Pattern Matching,我正在尝试在Scala列表上进行模式匹配,如果所需类型的对象包含在列表中的任何位置,则该模式将匹配 我试过: case _ :: (something: DesiredSubclass) :: _ => ??? 但这仅在我要查找的元素之前至少有一个元素时才匹配。如果存在,请使用保护和高阶方法 case xs if xs.exists(_.isInstanceOf[DesiredSubclass]) => ??? 如果保护与存在高阶方法一起使用 case xs if xs.exis

我正在尝试在Scala列表上进行模式匹配,如果所需类型的对象包含在列表中的任何位置,则该模式将匹配

我试过:

case _ :: (something: DesiredSubclass) :: _ => ???

但这仅在我要查找的元素之前至少有一个元素时才匹配。

如果
存在,请使用
保护和
高阶方法

case xs if xs.exists(_.isInstanceOf[DesiredSubclass]) => ???

如果
保护与
存在
高阶方法一起使用

case xs if xs.exists(_.isInstanceOf[DesiredSubclass]) => ???

使用公开的
来代替[SomeType]
是不好看的。最好使用
match
-类似
PartialFunction
的文字符号:

list.exists { case _: DesiredSubclass => true; case _ => false }

使用公开的
来代替[SomeType]
是不好看的。最好使用
match
-类似
PartialFunction
的文字符号:

list.exists { case _: DesiredSubclass => true; case _ => false }

模式匹配不能用于这样的任意搜索。你可以

list.collect{ case something: DesiredSubclass => something }.headOption
获取包含该项的选项。您不能在match语句中分配该类,但如果获取该特定类非常重要,您可以编写一个自定义提取器:

class DesiredSubclass(val s: String) {}
object FirstOfDesired {
  def unapply[A](xs: Seq[A]) = xs.collect{ case x: DesiredSubclass => x }.headOption
}
例如,现在:

val list = 7 :: (new DesiredSubclass("fish")) :: Nil
scala> list match { case FirstOfDesired(ds) => println(ds.s); case _ => }
fish

模式匹配不能用于这样的任意搜索。你可以

list.collect{ case something: DesiredSubclass => something }.headOption
获取包含该项的选项。您不能在match语句中分配该类,但如果获取该特定类非常重要,您可以编写一个自定义提取器:

class DesiredSubclass(val s: String) {}
object FirstOfDesired {
  def unapply[A](xs: Seq[A]) = xs.collect{ case x: DesiredSubclass => x }.headOption
}
例如,现在:

val list = 7 :: (new DesiredSubclass("fish")) :: Nil
scala> list match { case FirstOfDesired(ds) => println(ds.s); case _ => }
fish