Skip to content

Instantly share code, notes, and snippets.

@olafurpg
Created May 11, 2016 13:27
Show Gist options
  • Save olafurpg/c58a96cb44d90b339bf017312251bf76 to your computer and use it in GitHub Desktop.
Save olafurpg/c58a96cb44d90b339bf017312251bf76 to your computer and use it in GitHub Desktop.
Having fun with Scala extractor objects. The && combinator can be used to merge multiple extractors into one MEGA extractor.
object && {
def unapply[A](e: A) = Some(e -> e)
def test() {
val greaterThan10 = Find[Int](_ > 10)
List(1, 2, 11, 3) match {
// All must succeed
case greaterThan10(ten) && Last(last) && Head(head) =>
println(ten) // 11
println(last) // 3
println(head) // 1
case _ => println("Sorry")
}
}
}
object Head { def unapply[T](lst: List[T]) = lst.headOption }
case class Find[T](f: T => Boolean) { def unapply(lst: List[T]) = lst.find(f) }
object Last { def unapply[T](lst: List[T]) = lst.lastOption }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment