Reputation: 5270
I am wondering if and how I can use a match clause within a collectFirst clause in scala. So for example I want to do something like the following:
myCollection collectFirst {
case i =>
otherCollection.find(_ == i + 1) match {
case Some(j) => j
case None => // Check the next i???
}
}
Note I know I could achieve the above logic without the match clause but am doing it this way purely for explanatory purposes
Upvotes: 0
Views: 1642
Reputation: 5270
I defined a function as follows:
def mapFirst[A, B](seq: Seq[A])(f: A => Option[B]): Option[B] = seq match {
case Seq(a, rest @ _ *) =>
f(a) match {
case Some(b) => Some(b)
case None => mapFirst(rest)(f)
}
case _ => None
}
Which could be used thus:
mapFirst(myCollection) { i =>
otherCollection.find(_ == i + 1) match {
case Some(j) => Some(j)
case None => None
}
}
Upvotes: 0
Reputation: 1031
like this?
val other = List(4)
List(1, 2, 3, 4) collectFirst {
case i if other.contains(i) => s"other has $i"
}
res0: Option[String] = Some(other has 4)
Note I know I could achieve the above logic without the match clause but am doing it this way purely for explanatory purposes
List(1, 2, 3, 4) collectFirst {
case i if (other.find(_ == i) match {
case Some(_) => true
case None => false
}) => s"other has $i"
}
don't do that in your code!
Upvotes: 1