Created
May 6, 2011 15:33
-
-
Save momania/959172 to your computer and use it in GitHub Desktop.
Extractor pattern matching in partial function
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 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)) | |
} |
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
def partialWithCaseInExtractor: PartialFunction[Event, Int] = { | |
case MyExtractor() => 2 | |
case Event(Message, 1) => 1 | |
} |
I haven't ruled out pilot error, but typed extractors have some nasty bugs: http://lampsvn.epfl.ch/trac/scala/ticket/1697
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
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?