在 Scala 中,可以使用 match case 语句匹配多个值。这可以通过使用管道符 (|) 来实现。下面是一个示例:

val x = 3

x match {
  case 1 | 2 => println('x is either 1 or 2')
  case 3 | 4 => println('x is either 3 or 4')
  case _ => println('x is something else')
}

在这个例子中,我们使用了管道符来匹配 x 是否等于 1 或 2,或者是否等于 3 或 4。如果 x 不等于这些值,就会执行默认的情况,即打印'x is something else'。

需要注意的是,管道符只能用于匹配常量值,不能用于匹配变量或表达式。如果需要匹配多个变量或表达式,可以使用元组或 case 类。

Scala Match Case: 多值匹配指南

原文地址: https://www.cveoy.top/t/topic/oA6V 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录