9

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:

abstract case class Node(val blocks: (Node => Option[Node])*)
case class Root(val elementBlocks: (Node => Option[Node])*) extends Node(elementBlocks)

the above doesn't compile... is it actually possible to do this?

outis
  • 75,655
  • 22
  • 151
  • 221
p3t0r
  • 1,980
  • 1
  • 16
  • 22
  • sure, didn't have time to look at the answers earlier. – p3t0r Nov 02 '09 at 12:13
  • possible duplicate of [How to pass List to Int* method in scala?](http://stackoverflow.com/questions/12436392/how-to-pass-list-to-int-method-in-scala) – om-nom-nom Sep 15 '12 at 12:11
  • I've marked a new one question as *parent question* cause it's ask for general case, not only for case classes – om-nom-nom Sep 15 '12 at 12:12

2 Answers2

21

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)
oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
8

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.

Thomas Jung
  • 32,428
  • 9
  • 84
  • 114