Scala - Currying和默认参数

Lea*_*ner 10 arguments scala currying default-value

我有一个函数有两个参数列表,我试图部分应用和currying使用.第二个参数列表包含所有都具有默认值(但不是隐式)的参数.像这样的东西:

 def test(a: Int)(b: Int = 2, c: Int = 3) { println(a + ", " + b + ", " + c); }
Run Code Online (Sandbox Code Playgroud)

现在,以下几点都很好:

 test(1)(2, 3);
 test(1)(2);
 test(1)(c=3);
 test(1)();
Run Code Online (Sandbox Code Playgroud)

现在,如果我定义:

 def partial = test(1) _;
Run Code Online (Sandbox Code Playgroud)

然后可以完成以下操作:

 partial(2, 3);
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么我不能省略'部分'中的一些/所有参数,如下所示:

 partial(2);
 partial(c=3);
 partial();
Run Code Online (Sandbox Code Playgroud)

不应该写"部分"的行为与"test(1)"的行为基本相同吗?有人可以帮我找出实现这个目标的方法吗?

请帮忙,我很绝望!

编辑 - 由于我无法在24小时内回答我自己的问题,我将在此发表自己的答案:

到目前为止,这是我能做的最好的事情:

class Test2(val a: Int) {
   def apply(b: Int = 2, c: Int = 3) { println(a + ", " + b + ", " + c); }
}

def test2(a: Int) = new Test2(a);
def partial2 = test2(1); // Note no underscore

test2(1)(2, 3);
test2(1)(2);
test2(1)(c=3);
test2(1)();

partial2(2, 3)
partial2(2);
partial2(c=3);
partial2();
Run Code Online (Sandbox Code Playgroud)

这种方式有效......

Jea*_*let 6

类型推理引擎给出partial了下一步的类型; 即,eta扩张test(1) _.你可以在REPL中看到partial有类型(Int, Int) => Unit,但test有类型(a: Int)(b: Int,c: Int)Unit.eta扩展的结果是一个Function对象,它不带任何参数名称(因为它可以Function用匿名参数定义).

要解决此问题,您必须定义partial如下:

def partial(b: Int = 2, c: Int = 3) = test(1)(b,c)
Run Code Online (Sandbox Code Playgroud)

也许你会想要分析两者的默认值,test并且partial可以达到它们以确保它们保持平等.但我知道没有技巧可以避免重复参数的名称而不会引入额外的开销,比如创建新对象等.


Lea*_*ner 4

这是迄今为止我自己能做的最好的事情:

class Test2(val a: Int) {
   def apply(b: Int = 2, c: Int = 3) { println(a + ", " + b + ", " + c); }
}

def test2(a: Int) = new Test2(a);
def partial2 = test2(1); // Note no underscore

test2(1)(2, 3);
test2(1)(2);
test2(1)(c=3);
test2(1)();

partial2(2, 3)
partial2(2);
partial2(c=3);
partial2();
Run Code Online (Sandbox Code Playgroud)

这样就可以工作了...