本文介绍了案例类、模式匹配和可变参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这样的类层次结构:
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.
更多推荐
案例类、模式匹配和可变参数
发布评论