Java 和 Scala 都有可变参数,并且都只支持最后一个参数。
def varargTest(ints:Int*) { ints.foreach(println) }
来自this article,区别在于用于可变参数的类型:
- Java 数组
- Seq (Sequence) for Scala:它可以迭代,并且可以使用许多方法,例如集合 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 节提到:
参数部分的最后一个值参数可以后缀为“*”,例如
(..., x:T *).
那么方法内部这种重复参数的类型是
序列类型scala.Seq[T].
具有重复参数T* 的方法采用可变数量的T 类型参数。
(T1, . . . , Tn,S*)U => (T1, . . . , Tn,S, . . . , S)U,
此规则的唯一例外是如果最后一个参数通过_* 类型注释标记为序列参数。
(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: _*) }