将单个参数和Seq传递给可变参数函数

6

我知道可以向可变参数函数传递单个参数,也可以使用:_*传递一个序列,但是能否同时传递两者呢?

例如:

scala> object X { def y(s: String*) = println(s) }
defined module X

scala> X.y("a", "b", "c")
WrappedArray(a, b, c)

scala> X.y(Seq("a", "b", "c"):_*)
List(a, b, c)

scala> X.y("a", Seq("b", "c"):_*)
<console>:9: error: no `: _*' annotation allowed here
(such annotations are only allowed in arguments to *-parameters)
       X.y("a", Seq("b", "c"):_*)
                             ^

编辑:在Scala 2.10中(如果有关系的话)


6
你可以尝试使用X.y("a" +: Seq("b", "c") : _*)吗? - Impredicative
如果第一个参数正在被隐式转换为正确的类型,则此解决方案无效,有什么想法吗? - GentlemanHal
2个回答

5

此方法可能有些不规范,但它应该可以很好地工作:

X.y(Seq("a") ++ Seq("b", "c"):_*)

3

如果你仔细查看Scala标准库,你会发现在某些地方存在这样的模式:

def doIt(arg: Thing)
def doIt(arg1: Thing, arg2: Thing, moreArgs: Thing*)

你可以在Set.+(...)中看到这个特性。它允许你在重载时拥有任意数量的参数而不会产生歧义。 补充说明 概念证明:
scala> class DI { def doIt(i: Int) = 1; def doIt(i1: Int, i2: Int, iMore: Int*) = 2 + iMore.length }
defined class DI

scala> val di1 = new DI
di1: DI = DI@16ac0be1

scala> di1.doIt(0)
res1: Int = 1

scala> di1.doIt(1, 2)
res2: Int = 2

scala> di1.doIt(1, 2, 3)
res3: Int = 3

scala> di1.doIt(1, 2, List(3, 4, 5): _*)
res4: Int = 5

@om-nom-nom:不正确,已经证明了。 - Randall Schulz
“Set” 工厂没有这种重载模式。当我提到 “Set” 时,实际上是在看它的 “+” 方法。 - Randall Schulz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接