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
}
@momania
Copy link
Author

momania commented May 9, 2011

So, why doesn't first work, but if we change the partial function to the second example it does?
Why does the order matter when using regular cases in combination with extractors?

@retronym
Copy link

retronym commented May 9, 2011

I haven't ruled out pilot error, but typed extractors have some nasty bugs: http://lampsvn.epfl.ch/trac/scala/ticket/1697

@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