Case classes, pattern matching and varargs

前端 未结 3 690
执笔经年
执笔经年 2020-12-31 10:36

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
         


        
3条回答
  •  萌比男神i
    2020-12-31 10:55

    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"))
    

    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.

提交回复
热议问题