Scala - Currying 和默认参数 [英] Scala - Currying and default arguments

查看:23
本文介绍了Scala - Currying 和默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个参数列表的函数,我正在尝试部分应用并与 currying 一起使用.第二个参数列表包含所有具有默认值(但不是隐式)的参数.像这样:

I have a function with two parameter lists that I am trying to partially apply and use with currying. The second parameter list contains arguments that all have default values (but not implicit). Something like this:

 def test(a: Int)(b: Int = 2, c: Int = 3) { println(a + ", " + b + ", " + c); }

现在,以下一切正常:

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

现在如果我定义:

 def partial = test(1) _;

然后可以进行以下操作:

Then the following can be done:

 partial(2, 3);

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

Can someone explain why I can't omit some/all arguments in 'partial' as follows:

 partial(2);
 partial(c=3);
 partial();

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

Shouldn't writing "partial" behave essentially the same way as "test(1)"? Can someone please help me figure out a way to achieve this?

请帮忙,我很绝望!

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

EDIT - Since I can't answer my own question within 24 hours, I'll post my own answer here:

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

This is the best I could do myself so far:

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();

这样就可以了...

推荐答案

这是我目前能做的最好的事情:

This is the best I could do myself so far:

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();

这样就可以了...

这篇关于Scala - Currying 和默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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