Java 有:
public void someMethod(int ... intArray) { // question: what is the equivalent to "..."
// do something with intArray
}
如何在 Scala 中实现相同的功能?也就是向方法传递未定义数量的参数?
最佳答案
Java 和 Scala 都有可变参数,并且都只支持最后一个参数。
def varargTest(ints:Int*) { ints.foreach(println) }
来自 this article ,不同之处在于用于可变参数的类型:
- Java 数组
- Scala 的 Seq (Sequence):它可以迭代,并且可以使用许多方法,例如集合 foreach、map、filter、find...
“*”代表 0 个或多个参数。
注意:如果参数值已经被“打包”为序列,比如列表,则失败:
# varargTest(List(1,2,3,4,5))
# //--> error: type mismatch;
# //--> found : List[Int]
# //--> required: Int
# //--> varargTest(List(1,2,3,4,5))
# //-->
但这会过去的:
varargTest(List(1,2,3):_*)
//--> 1
//--> 2
//--> 3
'_
' 是类型推断的占位符快捷方式。
'_*
' 在这里适用于“重复类型”。
Scala Specification 第 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
.
(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]).
注意之二:注意 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: _*) }
关于java - Scala 如何在方法定义中接收多个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1438762/