extractor with unapplySeq
unapplySeq
unapply
returns Option[Tuple]
. It helps extract fixed number of parts. Whereas unapplySeq
returns Option[Seq[T]]
. The parts extracted are unknown until at runtime.
object VarArity {
def unapplySeq(s: String): Option[Seq[String]] = {
Some(s.split("-"))
}
def main(args: Array[String]): Unit = {
val str = "a-b-c"
str match {
case VarArity(a, remains@_*) => println(remains.size)
case VarArity(a, b, c) => println(a, b, c)
case VarArity(p @_*) => println(p.size)
}
}
}
Although only the first case is matched, the other cases in code illustrate what we can do to extract the parts.