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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I kind of prefer writing functions from (A => Option[B]), and chaining them together with Scalaz,..