语法糖:_* 用于将 Seq 视为方法参数
我刚刚在网络上的某个地方注意到这个构造:
val list = List(someCollection: _*)
_*
是什么意思?这是某些方法调用的语法糖吗?我的自定义类应该满足哪些约束才能利用此语法糖?
I just noticed this construct somewhere on web:
val list = List(someCollection: _*)
What does _*
mean? Is this a syntax sugar for some method call? What constraints should my custom class satisfy so that it can take advantage of this syntax sugar?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通常,
:
表示法用于类型归属,强制编译器将值视为某种特定类型。这与强制转换不太相同。在本例中,您将指定特殊的 varargs 类型。这反映了用于声明 varargs 参数的星号表示法,并且可以用于子类
Seq[T]
的任何类型的变量:Generally, the
:
notation is used for type ascription, forcing the compiler to see a value as some particular type. This is not quite the same as casting.In this case, you're ascribing the special varargs type. This mirrors the asterisk notation used for declaring a varargs parameter and can be used on a variable of any type that subclasses
Seq[T]
:这是用于分解数组的 scala 语法。某些函数采用可变数量的参数,并且要传入数组,您需要将
: _*
附加到数组参数。That's scala syntax for exploding an array. Some functions take a variable number of arguments and to pass in an array you need to append
: _*
to the array argument.变量(数量)参数使用 * 定义。
例如,
def wordcount(words: String*) = println(words.size)
wordcount 需要一个字符串作为参数,
但接受更多字符串作为其输入参数(类型归属需要 _*)
Variable (number of) Arguments are defined using *.
For example,
def wordcount(words: String*) = println(words.size)
wordcount expects a string as parameter,
but accepts more Strings as its input parameter (_* is needed for Type Ascription)