简体   繁体   English

将scala(2.8)case类中的可变数量的参数传递给父构造函数

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

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中的case类试验变量构造函数参数,但是我无法将它们传递给case类的父类的构造函数:

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? 以上不编译......实际上可以这样做吗?

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)

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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM