pass variable number of arguments in scala (2.8) case class to parent constructor

前端 未结 2 395
一向
一向 2020-12-16 03:42

I was experimenting with variable constructor arguments for case classes in Scala, but am unable to pass them to the constructor of a case classes\' parent:

         


        
相关标签:
2条回答
  • 2020-12-16 04:23

    This works with 2.7:

    abstract case class A(val a: String*)
    case class B(val b: String*) extends A(b:_*)
    

    Should work with 2.8.

    0 讨论(0)
  • 2020-12-16 04:32

    You need to use the :_* syntax which means "treat this sequence as a sequence"! Otherwise, your sequence of n items will be treated as a sequence of 1 item (which will be your sequence of n items).

    def funcWhichTakesSeq(seq: Any*) = println(seq.length + ": " + seq)
    
    val seq = List(1, 2, 3)
    funcWhichTakesSeq(seq)      //1: Array(List(1, 2, 3)) -i.e. a Seq with one entry
    funcWhichTakesSeq(seq: _*)  //3: List(1, 2, 3)
    
    0 讨论(0)
提交回复
热议问题