scala 语法糖:_* 用于将 Seq 视为方法参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4176440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:33:29  来源:igfitidea点击:

Syntax sugar: _* for treating Seq as method parameters

scalasyntactic-sugar

提问by user7865221

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?

什么_*意思?这是某些方法调用的语法糖吗?我的自定义类应该满足哪些约束才能利用这种语法糖?

回答by Kevin Wright

Generally, the :notation is used for type ascription, forcing the compiler to see a value as some particular type. This is not quitethe same as casting.

通常,该:符号用于类型归属,强制编译器将值视为某种特定类型。这不是一样的铸件。

val b = 1 : Byte
val f = 1 : Float
val d = 1 : Double

In this case, you're ascribing the special varargstype. 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]:

在这种情况下,您将归因于特殊的varargs类型。这反映了用于声明 varargs 参数的星号符号,可用于任何类型的子类变量Seq[T]

def f(args: String*) = ... //varargs parameter, use as an Array[String]
val list = List("a", "b", "c")
f(list : _*)

回答by David K.

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.

这是用于爆炸数组的 Scala 语法。某些函数采用可变数量的参数,要传入数组,您需要附加: _*到数组参数。

回答by GraceMeng

Variable (number of) Arguments are defined using *. For example,

变量(数量)参数使用 * 定义。例如,

def wordcount(words: String*) = println(words.size)

def wordcount(words: String*) = println(words.size)

wordcount expects a string as parameter,

wordcount 需要一个字符串作为参数,

scala> wordcount("I")
1

but accepts more Strings as its input parameter (_* is needed for Type Ascription)

但接受更多字符串作为其输入参数(类型归属需要 _*)

scala> val wordList = List("I", "love", "Scala")
scala> wordcount(wordList: _*)
3