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

发布于 2024-08-09 10:30:04 字数 268 浏览 3 评论 0原文

我正在尝试 Scala 中案例类的可变构造函数参数,但无法将它们传递给案例类父级的构造函数:

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

上面的内容无法编译...实际上可以做到这一点吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你如我软肋 2024-08-16 10:30:04

您需要使用 :_* 语法,这意味着“将此序列视为序列”!否则,您的 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)

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)
输什么也不输骨气 2024-08-16 10:30:04

这适用于 2.7:

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

应该适用于 2.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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文