`:_*`(冒号下划线星号)在 Scala 中做什么?
我有这个问题中的以下代码:
def addChild(n: Node, newChild: Node) = n match {
case Elem(prefix, label, attribs, scope, child @ _*) => Elem(prefix, label, attribs, scope, child ++ newChild : _*)
case _ => error("Can only add children to elements!")
}
一切其中非常清楚,除了这一段: child ++ newChild : _*
它有什么作用?
我知道有 Seq[Node]
与另一个 Node
连接,然后呢? : _*
的作用是什么?
I have the following piece of code from this question:
def addChild(n: Node, newChild: Node) = n match {
case Elem(prefix, label, attribs, scope, child @ _*) => Elem(prefix, label, attribs, scope, child ++ newChild : _*)
case _ => error("Can only add children to elements!")
}
Everything in it is pretty clear, except this piece: child ++ newChild : _*
What does it do?
I understand there is Seq[Node]
concatenated with another Node
, and then? What does : _*
do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它“splats”1序列。
查看
被调用的
构造函数签名,但这里只有一个序列,而不是
child1
、child2
等,因此这允许将结果序列用作输入到构造函数。1 这在 SLS 中没有一个可爱的名字,但这里是详细信息。重要的是它改变了 Scala 将参数绑定到具有重复参数的方法的方式(如上面的
Node*
所示)。_*
类型注释在SLS的“4.6.2重复参数”中介绍。It "splats"1 the sequence.
Look at the constructor signature
which is called as
but here there is only a sequence, not
child1
,child2
, etc. so this allows the result sequence to be used as the input to the constructor.1 This doesn't have a cutesy-name in the SLS, but here are the details. The important thing to get is that it changes how Scala binds the arguments to the method with repeated parameters (as denoted with
Node*
above).The
_*
type annotation is covered in "4.6.2 Repeated Parameters" of the SLS.child ++ newChild
- 序列:
- 类型归属,帮助编译器理解该表达式的类型的提示_*
- 占位符接受任何值 + vararg 运算符child ++ newChild : _*
将Seq[Node]
扩展为Node*
(告诉编译器我们正在而不是使用可变参数,而不是序列)。对于只能接受可变参数的方法特别有用。child ++ newChild
- sequence:
- type ascription, a hint that helps compiler to understand, what type does that expression have_*
- placeholder accepting any value + vararg operatorchild ++ newChild : _*
expandsSeq[Node]
toNode*
(tells the compiler that we're rather working with a varargs, than a sequence). Particularly useful for the methods that can accept only varargs.上面的所有答案看起来都很棒,但只需要一个示例来解释这一点。
如下:
现在我们知道
:_*
的作用是告诉编译器:请解压此参数并将这些元素绑定到函数调用中的 vararg 参数,而不是将 x 作为单个参数。简而言之,
:_*
是为了消除将参数传递给 vararg 参数时的歧义。All the above answer looks great, but just need a sample to explain this .
Here it is :
So now we know what
:_*
do is to tell compiler : please unpack this argument and bind those elements to the vararg parameter in function call rather than take the x as a single argument .So in a nutshell, the
:_*
is to remove ambiguity when pass argument to vararg parameter.对于像我这样的懒人来说,它只是将集合值转换为 varArgs!
For some of the lazy folks like me, it just converts collection values to varArgs!