scala 将Scala(2.8)案例类中可变数量的参数传递给父构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1660339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pass variable number of arguments in scala (2.8) case class to parent constructor
提问by p3t0r
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:
我正在 Scala 中试验案例类的可变构造函数参数,但无法将它们传递给案例类的父类的构造函数:
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?
上面没有编译......实际上可以这样做吗?
采纳答案by Thomas Jung
This works with 2.7:
这适用于 2.7:
abstract case class A(val a: String*)
case class B(val b: String*) extends A(b:_*)
Should work with 2.8.
应该与 2.8 一起使用。
回答by oxbow_lakes
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).
您需要使用:_*表示“将此序列视为序列”的语法!否则,您的 n 个项目的序列将被视为 1 个项目的序列(这将是您的 n 个项目的序列)。
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)

