在 Scala 中,我可以将重复的参数传递给其他方法吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2835956/
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
In scala can I pass repeated parameters to other methods?
提问by Fred Haslam
Here is something I can do in java, take the results of a repeated parameter and pass it to another method:
这是我可以在 java 中做的事情,获取重复参数的结果并将其传递给另一个方法:
public void foo(String ... args){bar(args);}
public void bar(String ... args){System.out.println("count="+args.length);}
In scala it would look like this:
在 Scala 中,它看起来像这样:
def foo(args:String*) = bar(args)
def bar(args:String*) = println("count="+args.length)
But this won't compile, the bar signature expects a series of individual strings, and the args passed in is some non-string structure.
但这不会编译,bar 签名需要一系列单独的字符串,传入的 args 是一些非字符串结构。
For now I'm just passing around arrays. It would be very nice to use starred parameters. Is there some way to do it?
现在我只是传递数组。使用带星号的参数会非常好。有什么方法可以做到吗?
回答by retronym
Java makes an assumption that you want to automatically convert the Array argsto varargs, but this can be problematic with methods that accept varargs of type Object.
Java 假设您希望将 Array 自动转换args为可变参数,但这对于接受 Object 类型的可变参数的方法可能会出现问题。
Scala requires that you be explicit, by ascribing the argument with : _*.
Scala 要求你是明确的,通过将参数归因于: _*.
scala> def bar(args:String*) = println("count="+args.length)
bar: (args: String*)Unit
scala> def foo(args:String*) = bar(args: _*)
foo: (args: String*)Unit
scala> foo("1", "2")
count=2
You can use : _*on any subtype of Seq, or on anything implicitly convertable to a Seq, notably Array.
您可以: _*在 的任何子类型上使用Seq,或者在任何可隐式转换为 a 的东西上使用Seq,尤其是Array.
scala> def foo(is: Int*) = is.length
foo: (is: Int*)Int
scala> foo(1, 2, 3)
res0: Int = 3
scala> foo(Seq(1, 2, 3): _*)
res1: Int = 3
scala> foo(List(1, 2, 3): _*)
res2: Int = 3
scala> foo(Array(1, 2, 3): _*)
res3: Int = 3
scala> import collection.JavaConversions._
import collection.JavaConversions._
scala> foo(java.util.Arrays.asList(1, 2, 3): _*)
res6: Int = 3
It is explained well with examples in the Language Reference, in section 4.6.2.
语言参考4.6.2 节中的示例对其进行了很好的解释。
Note that these examples are made with Scala 2.8.0.RC2.
请注意,这些示例是使用 Scala 2.8.0.RC2 制作的。

