Created
July 5, 2018 11:11
-
-
Save JoolsF/09a0f9dc5e30afef3e34242a5fe2ac04 to your computer and use it in GitHub Desktop.
Unapply example 1
This file contains hidden or 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
| sealed trait Thing { | |
| val id: Int | |
| } | |
| case class ThingOne(id: Int) extends Thing | |
| case class ThingTwo(id: Int, code: String) extends Thing | |
| object Thing { | |
| object WithCode { | |
| def unapply(arg: ThingTwo): Option[String] = Some(arg.code) | |
| } | |
| } | |
| case class ThingWithCode(code: String) | |
| /** | |
| * Matching on Thing using custom unapply to extract a field not present in super type | |
| * @param t | |
| * @return | |
| */ | |
| def getThing(t: Thing) = t match { | |
| case Thing.WithCode(code) => ThingWithCode(code) | |
| case t => ThingWithCode("foobar") | |
| } | |
| getThing(ThingOne(1)) // ThingWithCode(foobar) | |
| getThing(ThingTwo(2, "xyz")) // ThingWithCode(xyz) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment