下面是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")
}
}我不明白为什么vals之前一定要有val1,所以我稍微修改了一下代码:
// 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有什么很好的理由吗
发布于 2015-06-18 16:44:46
假设使用vals @ _*的匹配项可以包含0个或更多条目,那么这个初始变量的效果就是强制要求提供至少一个值。
这篇博客文章详细介绍了与方法参数相关的a similar trick
https://stackoverflow.com/questions/30910455
复制相似问题