小编dac*_*142的帖子

Scala案例类匹配是否可以使用命名参数?

假设有一个Scala案例类 Point

case class Point(x: Int, y: Int)
Run Code Online (Sandbox Code Playgroud)

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

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

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

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


val flag = p match {
  case Point(x,_,_,_,_,) if x>0 => true
  ......
}
Run Code Online (Sandbox Code Playgroud)

是否有类似以下代码的语法糖?

val flag = p match {
  case Point(x0=x) if x>0 => true
  ......
}
Run Code Online (Sandbox Code Playgroud)

scala wildcard pattern-matching case-class

6
推荐指数
1
解决办法
142
查看次数

标签 统计

case-class ×1

pattern-matching ×1

scala ×1

wildcard ×1