为什么*-参数必须放在最后?
从技术上讲,即使 *-参数不限于最后一个,编译器也应该能够弄清楚。这个SO link 提供了一些关于可能的基本原理的见解(尽管是非官方的)。
为什么 *-parameter 不能放在默认参数之后?
如果允许在默认参数之后使用 *-parameter,则在某些情况下,应为参数变量分配所提供的参数会产生歧义。例如:
def foo(a: String = "hi", bs: String*) = a + " " + bs.mkString(" ")
foo("hello", "world") // Should "hello" go to `a` or be a part of `bs`?
请注意,从技术上讲,这种限制也可以取消,例如,在出现歧义的情况下需要明确的参数变量分配(例如foo(a="hello", "world"))。
为了规避限制,您可以使用柯里化(它允许您为每个参数列表提供一个 * 参数):
def bar(s: String, i: Int = 1, ts: (String, String)*) =
ts.map(t => (t._1 + s*i, t._1 + s*i))
// <console>:23: error: a parameter section with a `*'-parameter is not allowed to have default arguments
// def bar(s: String, i: Int = 1, ts: (String, String)*) = {
def bar(s: String, i: Int = 1)(ts: (String, String)*) =
ts.map(t => (t._1 + s*i, t._2 + s*i))
bar("!", 2)(("a", "b"), ("c", "d"))
// res1: Seq[(String, String)] = ArrayBuffer((a!!,b!!), (c!!,d!!))