Alexander Ioffe
06/05/2023, 1:01 PM// Scala Style Unapply function:
sealed trait Name
case class SimpleName(first: String, last: String) extends Name
case class FullName(first: String, middle: String, last: String) extends Name
object FirstLast {
def unapply(name: Name): Option[(String, String)] = name match {
case SimpleName(first, last) => Some(first, last)
case FullName(first, _, last) => Some(first, last)
case _ => None
}
}
val p: Person = ...
p match {
case Person(FirstLast("Joe", last), age) => ...
}
In Decomat:
object FirstLast {
operator fun get(first: Pattern0<String>, last: Pattern0<String>) =
customPattern2(first, last) { it: Name ->
on(it).match(
case(FullName[Is(), Is()])
.then { first, last -> Components2(first, last) },
case(SimpleName[Is(), Is()])
.then { first, last -> Components2(first, last) }
)
}
}
// Then use the `FirstLast` custom pattern to match and extract data
val p: Person = ...
val out =
on(p).match(
case(Person[FirstLast[Is("Joe"), Is()], Is()]).then { (first, last), age -> ... }
)
https://github.com/exoquery/decomat