Suppose there is a Scala case-class Point
case class Point(x: Int, y: Int)
One can use a wildcard for matching:
val p = new Point(1,2)
val inRightHalfPlane = p match {
case Point(x, _) if x>0 => true
case _ => false
}
However, if the number of members increase, one will need to use more wildcards _
:
case class Point(
x0: Int,
x1: Int,
x2: Int,
x3: Int,
x4: Int,
)
val flag = p match {
case Point(x,_,_,_,_,) if x>0 => true
......
}
Is there any syntax sugar like the following code?
val flag = p match {
case Point(x0=x) if x>0 => true
......
}
Case classes are Scala's way to allow pattern matching on objects without requiring a large amount of boilerplate. In the common case, all you need to do is add a single case keyword to each class that you want to be pattern matchable.
Notes. Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes. Scala also allows the definition of patterns independently of case classes, using unapply methods in extractor objects.
It is defined in Scala's root class Any and therefore is available for all objects. The match method takes a number of cases as an argument. Each alternative takes a pattern and one or more expressions that will be performed if the pattern matches. A symbol => is used to separate the pattern from the expressions.
You can define custom unapply
case class Point(
x0: Int,
x1: Int,
x2: Int,
x3: Int,
x4: Int,
)
object PositiveFirst {
def unapply(p: Point): Option[Int] = if (p.x0 > 0) Some(p.x0) else None
}
val p: Point = ???
val flag = p match {
case PositiveFirst(x) => true
// ......
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With