Skip to content

Instantly share code, notes, and snippets.

@JoolsF
Created July 5, 2018 11:11
Show Gist options
  • Select an option

  • Save JoolsF/09a0f9dc5e30afef3e34242a5fe2ac04 to your computer and use it in GitHub Desktop.

Select an option

Save JoolsF/09a0f9dc5e30afef3e34242a5fe2ac04 to your computer and use it in GitHub Desktop.
Unapply example 1
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