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

编程入门 行业动态 更新时间:2024-10-28 16:29:29
本文介绍了案例类、模式匹配和可变参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

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

本文发布于:2023-11-25 07:40:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628900.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:案例   参数   模式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!