案例类、模式匹配和可变参数 [英] Case classes, pattern matching and varargs
本文介绍了案例类、模式匹配和可变参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这样的类层次结构:
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.
这篇关于案例类、模式匹配和可变参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文