在 Scala 中,我可以将重复的参数传递给其他方法吗? [英] In scala can I pass repeated parameters to other methods?

查看:38
本文介绍了在 Scala 中,我可以将重复的参数传递给其他方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我可以在java中做的事情,获取重复参数的结果并将其传递给另一个方法:

Here is something I can do in java, take the results of a repeated parameter and pass it to another method:

public void foo(String ... args){bar(args);}
public void bar(String ... args){System.out.println("count="+args.length);}

在 Scala 中,它看起来像这样:

In scala it would look like this:

def foo(args:String*) = bar(args)
def bar(args:String*) = println("count="+args.length)

但这不会编译,bar 签名需要一系列单独的字符串,传入的 args 是一些非字符串结构.

But this won't compile, the bar signature expects a series of individual strings, and the args passed in is some non-string structure.

现在我只是传递数组.使用带星号的参数会非常好.有什么办法吗?

For now I'm just passing around arrays. It would be very nice to use starred parameters. Is there some way to do it?

推荐答案

Java 假设您希望自动将数组 args 转换为可变参数,但这对于接受可变参数的方法可能会出现问题对象类型.

Java makes an assumption that you want to automatically convert the Array args to varargs, but this can be problematic with methods that accept varargs of type Object.

Scala 要求您通过使用 : _* 指定参数来明确.

Scala requires that you be explicit, by ascribing the argument with : _*.

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

您可以在 Seq 的任何子类型上使用 : _*,或者在任何可隐式转换为 Seq 的东西上使用,特别是 Array.

You can use : _* on any subtype of Seq, or on anything implicitly convertable to a Seq, notably 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

通过语言参考中的示例进行了很好的解释,在第 4.6.2 节中.

It is explained well with examples in the Language Reference, in section 4.6.2.

请注意,这些示例是使用 Scala 2.8.0.RC2 制作的.

Note that these examples are made with Scala 2.8.0.RC2.

这篇关于在 Scala 中,我可以将重复的参数传递给其他方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆