Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import scala.collection.generic.CanBuildFrom
object Batik extends App {
val fun: Int => Option[Int] = {
case 3 => Some(1337)
case 5 => None
case n => Some(n * 3)
}
val mustare = List(1,2,3,4,5).filterMap(fun)
val setMust = Set(1,2,3,4,5).filterMap(fun)
val mustSeq: IndexedSeq[Int] = List(1,2,3,4,5).filterMap(fun)(scala.collection.breakOut)
println(mustare)
println(setMust)
println(mustSeq)
implicit class SeqW[CC[X] <: TraversableOnce[X], T](val seq: CC[T]) extends AnyVal {
def filterMap[U, TO](fun: T => Option[U])(implicit cbf: CanBuildFrom[CC[T], U, TO]): TO = {
val b = cbf()
seq.foreach{ fun(_).foreach{ b+= } }
b.result()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.