Java Scala 如何在方法定义中接收多个参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1438762/
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
How can Scala receive multiple parameters in a method definition?
提问by dankilman
Java has:
Java有:
public void someMethod(int ... intArray) { // question: what is the equivalent to "..."
// do something with intArray
}
how can I achieve the same functionality in Scala? That is, passing an undefined number of parameters to a method?
如何在 Scala 中实现相同的功能?也就是说,将未定义数量的参数传递给方法?
采纳答案by Joe
def someMethod(values : Int*)
Gives an array. Put the variable argument parameter as the last formal parameter.
给出一个数组。将可变实参作为最后一个形参。
回答by VonC
Both Java and Scala have varargs, and both only support it for the last parameters.
Java 和 Scala 都有可变参数,并且都只支持最后一个参数。
def varargTest(ints:Int*) { ints.foreach(println) }
From this article, the difference is in the type used for the varargs arguments:
在这篇文章中,不同之处在于用于 varargs 参数的类型:
- array for Java
- Seq (Sequence) for Scala: it can be iterated and many methods such as collections foreach, map, filter, find, ... are available
- Java 数组
- Seq (Sequence) for Scala:可以迭代,有很多方法,例如集合foreach、map、filter、find、...
The '*' stands for 0 or more arguments.
'*' 代表 0 个或多个参数。
Note: if the parameter values are already "packaged" as a sequence, such as a list, it fails:
注意:如果参数值已经“打包”为一个序列,比如列表,则失败:
# varargTest(List(1,2,3,4,5))
# //--> error: type mismatch;
# //--> found : List[Int]
# //--> required: Int
# //--> varargTest(List(1,2,3,4,5))
# //-->
But this will pass:
但这会过去:
varargTest(List(1,2,3):_*)
//--> 1
//--> 2
//--> 3
'_
' is a placeholder shortcut for type inference.
'_*
' is here applyied to a 'repeated type.
Section 4.6.2 of Scala Specificationmentions:
' _
' 是类型推断的占位符快捷方式。' _*
' 在这里适用于 ' 重复类型。Scala 规范的
第 4.6.2 节提到:
The last value parameter of a parameter section may be suffixed by “
*”
, e.g.(..., x:T *)
.
The type of such a repeated parameter inside the method is then the sequence typescala.Seq[T]
.
Methods with repeated parametersT*
take a variable number of arguments of typeT
.
参数部分的最后一个值参数可以后缀“
*”
,例如(..., x:T *)
。
方法内这种重复参数的类型就是序列类型scala.Seq[T]
。
具有重复参数的方法采用T*
可变数量的类型参数T
。
(T1, . . . , Tn,S*)U => (T1, . . . , Tn,S, . . . , S)U,
The only exception to this rule is if the last argument is marked to be a sequence argument via a
_*
type annotation.
此规则的唯一例外是如果最后一个参数通过
_*
类型注释标记为序列参数。
(e1, . . . , en,e0: _*) => (T1, . . . , Tn, scala.Seq[S]).
Note bis: beware of the underlying type erasure of Java:
注意之二:注意 Java 的底层类型擦除:
//--> error: double definition:
//--> method varargTest:(ints: Seq[Int])Unit and
//--> method varargTest:(ints: Int*)Unit at line 10
//--> have same type after erasure: (ints: Sequence)Unit
//--> def varargTest(ints:Seq[Int]) { varargTest(ints: _*) }