【问题标题】:Is it possible to use named parameter for Scala case-class matching? [duplicate]是否可以使用命名参数进行 Scala 案例类匹配? [复制]
【发布时间】:2019-09-26 09:22:52
【问题描述】:

假设有一个 Scala 案例类Point

case class Point(x: Int, y: Int)

可以使用通配符进行匹配:

val p = new Point(1,2)
val inRightHalfPlane = p match {
  case Point(x, _) if x>0 => true
  case _ => false
}

但是,如果成员数量增加,则需要使用更多的通配符_

case class Point(
  x0: Int,
  x1: Int,
  x2: Int,
  x3: Int,
  x4: Int,
)


val flag = p match {
  case Point(x,_,_,_,_,) if x>0 => true
  ......
}

有没有类似下面代码的语法糖?

val flag = p match {
  case Point(x0=x) if x>0 => true
  ......
}

【问题讨论】:

标签: scala pattern-matching wildcard case-class


【解决方案1】:

您可以自定义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
//      ......
  }

【讨论】:

  • ``` def unapply(p: Point): Boolean = p.x0 > 0 ... case PositiveFirst => true ```
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 2020-08-19
  • 2013-10-08
  • 2011-01-17
  • 2013-12-05
  • 1970-01-01
相关资源
最近更新 更多