Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use named parameter for Scala case-class matching? [duplicate]

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
  ......
}
like image 806
dacapo1142 Avatar asked May 08 '19 15:05

dacapo1142


People also ask

Which method of case class allows using objects in pattern matching?

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.

Does scala have pattern matching?

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.

What is case class and pattern matching in scala?

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.


1 Answers

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
//      ......
  }
like image 197
Dmytro Mitin Avatar answered Oct 10 '22 10:10

Dmytro Mitin