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

末鹿安然 提交于 2019-11-27 16:27:17

问题


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?


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/1660339/pass-variable-number-of-arguments-in-scala-2-8-case-class-to-parent-constructo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!