Skip to content

Instantly share code, notes, and snippets.

@momania
Created May 6, 2011 15:33
Show Gist options
  • Save momania/959172 to your computer and use it in GitHub Desktop.
Save momania/959172 to your computer and use it in GitHub Desktop.
Extractor pattern matching in partial function
object ExtractionTest extends Application {
case object Message
case class Event(event: Any, data: Int)
def partialWithNormalCase: PartialFunction[Event, Int] = {
case Event(Message, 1) => 1
case Event(Message, 2) => 2
}
def partialWithCaseInExtractor: PartialFunction[Event, Int] = {
case Event(Message, 1) => 1
case MyExtractor() => 2
}
object MyExtractor {
def unapply(event: Event) = {
event match {
case Event(Message, 2) => true
case _ => false
}
}
}
val eventMessageTwo = Event(Message, 2)
val definedInPartialNormal = partialWithNormalCase.isDefinedAt(eventMessageTwo)
println("defined in normal: " + definedInPartialNormal)
println("applied in normal: " + partialWithNormalCase.apply(eventMessageTwo))
val definedInPartialWithExtractor = partialWithCaseInExtractor.isDefinedAt(eventMessageTwo)
println("defined in extractor: " + definedInPartialWithExtractor)
println("applied in extractor: " + partialWithCaseInExtractor.apply(eventMessageTwo))
}
def partialWithCaseInExtractor: PartialFunction[Event, Int] = {
case MyExtractor() => 2
case Event(Message, 1) => 1
}
@retronym
Copy link

retronym commented May 9, 2011

I kind of prefer writing functions from (A => Option[B]), and chaining them together with Scalaz,..

f >=> g >=> e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment