Thom Shutt
Thom Shutt

Reputation: 449

Matching an object somewhere in a Scala List

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

Answers (3)

Rex Kerr
Rex Kerr

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

Randall Schulz
Randall Schulz

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

missingfaktor
missingfaktor

Reputation: 92106

Use an if guard along with the exists higher order method.

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

Upvotes: 4

Related Questions