案例类、模式匹配和可变参数

案例类、模式匹配和可变参数

问题描述:

假设我有这样的类层次结构:

Let's say I have such class hierarchy:

abstract class Expr
case class Var(name: String) extends Expr
case class ExpList(listExp: List[Expr]) extends Expr

像这样定义ExpList的构造函数会更好吗:

Would it be better to define constructor of ExpList like this:

case class ExpList(listExp: Expr*) extends Expr

我想知道,每个定义在模式匹配方面的缺点/优点是什么?

I would like to know, what are drawbacks/benefits of each definitions regards pattern matching?

您可以同时拥有两个构造函数:

You can have both constructors:

case class ExpList(listExp: List[Expr]) extends Expr
object ExpList {
  def apply(listExp: Expr*) = new ExpList(listExp.toList)
}

//now you can do
ExpList(List(Var("foo"), Var("bar")))
//or
ExpList(Var("foo"), Var("bar"))

可变参数被转换为 mutable.WrappedArray,所以为了符合 case 类不可变的约定,你应该使用一个列表作为实际值.

Variadic arguments are converted to a mutable.WrappedArray, so to keep in line with the convention of case classes being immutable, you should use a list as the actual value.