Reputation: 449
I'm trying to pattern match on a Scala list with a pattern that will match if an object of the desired type is contained anywhere within the list.
I tried:
case _ :: (something: DesiredSubclass) :: _ => ???
But this only matches if there is at least one element before the one that I'm looking for.
Upvotes: 1
Views: 627
Reputation: 167911
Pattern matching can't be used to do arbitrary searches like that. You can
list.collect{ case something: DesiredSubclass => something }.headOption
to get an option with the item in it. You can't assign this within the match statement, but if it's really important to get that particular class, you can write a custom extractor:
class DesiredSubclass(val s: String) {}
object FirstOfDesired {
def unapply[A](xs: Seq[A]) = xs.collect{ case x: DesiredSubclass => x }.headOption
}
Now, for example:
val list = 7 :: (new DesiredSubclass("fish")) :: Nil
scala> list match { case FirstOfDesired(ds) => println(ds.s); case _ => }
fish
Upvotes: 1
Reputation: 26486
Use of overt isInstanceOf[SomeType]
is unsightly. Using the match
-like PartialFunction
literal notation is preferable:
list.exists { case _: DesiredSubclass => true; case _ => false }
Upvotes: 4
Reputation: 92106
Use an if
guard along with the exists
higher order method.
case xs if xs.exists(_.isInstanceOf[DesiredSubclass]) => ???
Upvotes: 4