java - Scala 如何在方法定义中接收多个参数?

标签 java scala variadic-functions

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 type scala.Seq[T].
Methods with repeated parameters T* take a variable number of arguments of type 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]).

注意之二:注意 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/

相关文章:

用 JavaScript 编写的 Java 解析器

java - IntelliJ IDEA 可以显示像eclipse 这样的maven 项目吗?

scala - SonarQube 的 Scala 配置文件在哪里?

java - 如何将 Java varargs 与 GWT Javascript native 接口(interface)一起使用? (又名, "GWT has no printf()")

c++ - 具有可变参数的 C 函数崩溃

java - JFileChooser - 关于 "open"和 "cancel"按钮。 java

java - 为什么 List<List<Integer>> 会更新,即使它不是全局变量?

scala - DI 或服务定位器 : Injecting implementations at run-time ( no static binding ) in scala

scala - Scala 中奇怪的类型不匹配

c++ _vsnprintf 意外的格式字符串