以下是Programming Scala本书中的一个示例:
// src/main/scala/progscala2/patternmatching/match-vararglist.sc
// Operators for WHERE clauses
object Op extends Enumeration { // <1>
type Op = Value
val EQ = Value("=")
val NE = Value("!=")
val LTGT = Value("<>")
val LT = Value("<")
val LE = Value("<=")
val GT = Value(">")
val GE = Value(">=")
}
import Op._
// Represent a SQL "WHERE x op value" clause, where +op+ is a
// comparison operator: =, !=, <>, <, <=, >, or >=.
case class WhereOp[T](columnName: String, op: Op, value: T) // <2>
// Represent a SQL "WHERE x IN (a, b, c, ...)" clause.
case class WhereIn[T](columnName: String, val1: T, vals: T*) // <3>
val wheres = Seq( // <4>
WhereIn("state", "IL", "CA", "VA"),
WhereOp("state", EQ, "IL"),
WhereOp("name", EQ, "Buck Trends"),
WhereOp("age", GT, 29))
for (where <- wheres) {
where match {
case WhereIn(col, val1, vals @ _*) => // <5>
val valStr = (val1 +: vals).mkString(", ")
println (s"WHERE $col IN ($valStr)")
case WhereOp(col, op, value) => println (s"WHERE $col $op $value")
case _ => println (s"ERROR: Unknown expression: $where")
}
}
我不明白为什么val1
之前必须有vals
,所以我修改了一下代码:
// Represent a SQL "WHERE x IN (a, b, c, ...)" clause.
case class WhereIn[T](columnName: String, vals: T*) // <3>
val wheres = Seq( // <4>
WhereIn("state", "IL", "CA", "VA"),
WhereOp("state", EQ, "IL"),
WhereOp("name", EQ, "Buck Trends"),
WhereOp("age", GT, 29))
for (where <- wheres) {
where match {
case WhereIn(col, vals @ _*) => // <5>
val valStr = vals.mkString(", ")
println (s"WHERE $col IN ($valStr)")
case WhereOp(col, op, value) => println (s"WHERE $col $op $value")
case _ => println (s"ERROR: Unknown expression: $where")
}
}
嗯,这给出了完全相同的输出。作者是否有任何理由添加val1
?
答案 0 :(得分:3)
鉴于使用vals @ _*
的匹配可以包含0个或更多条目,该初始变量具有强制必须提供至少一个值的效果。
此博客条目详细说明了与方法参数相关的a similar trick