Skip to content

Instantly share code, notes, and snippets.

@Arneball
Created January 21, 2014 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Arneball/8541738 to your computer and use it in GitHub Desktop.
Save Arneball/8541738 to your computer and use it in GitHub Desktop.
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