Extractors
A pattern such as Point(x, y) works because an object named Point has an unapply method. A case class gets that method from the compiler; any other object can provide one, and then its name is a pattern too. That is the whole mechanism behind extractors, and it is why a library can add a pattern without touching the type it matches.
An unapply that returns an Option
Halves answers Some(n / 2) for an even number and None for an odd one, so the pattern fits only where the extractor succeeds. Digits returns a Boolean, which is the form for a test with no values to bind:
extractors.scala
object Halves:
def unapply(n: Int): Option[Int] = if n % 2 == 0 then Some(n / 2) else None
object Digits:
def unapply(text: String): Boolean = text.nonEmpty && text.forall(_.isDigit)
@main def extractors(): Unit =
val numbers = List(2, 3, 10, 11)
numbers.foreach {
case Halves(half) => println(s"$half")
case n => println(s"$n is odd")
}
List("42", "four2", "").foreach {
case Digits() => println("all digits")
case text => println(s"not a number: [$text]")
}
scala-cli run --server=false extractors.scala
1
3 is odd
5
11 is odd
all digits
not a number: [four2]
not a number: []
Some and None decide which branch runs, and the value inside Some is what half binds. A Boolean extractor binds nothing, so its pattern is written with empty parentheses. Both forms work in a match and in the partial function a foreach takes.
Several values, a sequence and a regex
An unapply that returns a tuple binds several values at once, and unapplySeq binds a number of values the pattern decides. scala.util.matching.Regex is an extractor of the second kind, which is why a regular expression can be matched directly:
names.scala
object FullName:
def unapply(name: String): Option[(String, String)] =
name.split(" ") match
case Array(first, last) => Some((first, last))
case _ => None
object Csv:
def unapplySeq(line: String): Option[Seq[String]] = Some(line.split(",").toSeq)
val Pattern = raw"(\d+)-(\d+)".r
@main def custom(): Unit =
"Ada Lovelace" match
case FullName(first, last) => println(s"first: $first, last: $last")
case other => println(s"no full name: $other")
"a,b,c" match
case Csv(first, rest*) => println(s"first column $first, ${rest.length} more")
case line => println(line)
"12-34" match
case Pattern(left, right) => println(s"$left and $right")
case text => println(s"no match: $text")
scala-cli run --server=false names.scala
first: Ada, last: Lovelace
first column a, 2 more
12 and 34
FullName(first, last) binds the pair the extractor returned, and Csv(first, rest*) takes the first column and the rest into a sequence. Pattern(left, right) works because every Regex has an unapplySeq over its groups: a match on a compiled pattern is the readable form of a group extraction, and no group(1) call is written by hand.
Related
- Objects and companions: the unapply of a companion object.
- Pattern matching: the match an extractor is used in.
- Case classes: the extractor the compiler writes.
- Strings and interpolation: the raw string a regular expression is written in.
Автор статьи: Arthur Isaev