param: _* 在 Scala 中是什么意思? [英] What does param: _* mean in Scala?
问题描述
作为 Scala (2.9.1) 的新手,我有一个 List[Event]
并且想将它复制到一个 Queue[Event]
,但以下内容语法产生一个 Queue[List[Event]]
代替:
Being new to Scala (2.9.1), I have a List[Event]
and would like to copy it into a Queue[Event]
, but the following Syntax yields a Queue[List[Event]]
instead:
val eventQueue = Queue(events)
出于某种原因,以下有效:
For some reason, the following works:
val eventQueue = Queue(events : _*)
但我想了解它的作用,以及它为什么起作用?我已经看过 Queue.apply
函数的签名:
But I would like to understand what it does, and why it works? I already looked at the signature of the Queue.apply
function:
def apply[A](elems: A*)
我明白为什么第一次尝试不起作用,但第二次尝试是什么意思?什么是 :
和 _*
在这种情况下,为什么 apply
函数不只采用 Iterable[A]
?
And I understand why the first attempt doesn't work, but what's the meaning of the second one? What is :
, and _*
in this case, and why doesn't the apply
function just take an Iterable[A]
?
推荐答案
a: A
是类型归属;参见 Scala 中类型归属的目的是什么?
: _*
是类型归属的特殊实例,它告诉编译器将序列类型的单个参数视为可变参数序列,即 varargs.
: _*
is a special instance of type ascription which tells the compiler to treat a single argument of a sequence type as a variable argument sequence, i.e. varargs.
使用 Queue.apply
创建一个 Queue
是完全有效的,该Queue.apply
具有单个元素是序列或可迭代的,所以这正是当你给单个 Iterable[A]
.
It is completely valid to create a Queue
using Queue.apply
that has a single element which is a sequence or iterable, so this is exactly what happens when you give a single Iterable[A]
.
这篇关于param: _* 在 Scala 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!