Case classes, pattern matching and varargs

前端 未结 3 668
执笔经年
执笔经年 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条回答
  •  伪装坚强ぢ
    2020-12-31 11:07

    Just as a comment to Dan's solution: If you have this inside a function it does, due to the bug in Scala not work https://issues.scala-lang.org/browse/SI-3772. You get something like:

    scala> :paste
    // Entering paste mode (ctrl-D to finish)
        def g(){
            class Expr {}
            case class ExpList(listExp: List[Expr]) extends Expr
            object ExpList {
              def apply(listExp: Expr*) = new ExpList(listExp.toList)
            }
        }
    // Exiting paste mode, now interpreting.
    
    :10: error: ExpList is already defined as (compiler-generated) case cla
    ss companion object ExpList
                        object ExpList {
                               ^
    

    For now the workaround is simply to put the object first.

    scala> :paste
    // Entering paste mode (ctrl-D to finish)
        def g(){
            class Expr {}
            object ExpList {
              def apply(listExp: Expr*) = new ExpList(listExp.toList)
            }
            case class ExpList(listExp: List[Expr]) extends Expr
        }
    
    // Exiting paste mode, now interpreting.
    g: ()Unit
    

    I hope that will prevent people from stumbling over this bug as I did.

提交回复
热议问题