Created
May 11, 2016 13:27
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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