如何使匿名函数中的多个参数隐式? [英] How can I make multiple parameters in an anonymous function implicit?
问题描述
如果我们有一个接受匿名函数的方法 A =>B
作为参数,我们可以让 A
隐含在我们的调用中.
If we have a method that accepts an anonymous function A => B
as a parameter, we can make A
implicit in our invocation.
def impl(a: Int)(f: Int => Int): Int = f(a)
impl(a) { implicit z =>
...
}
但是我们可以使用具有多个参数的匿名函数来做到这一点吗?
But can we do this with anonymous functions that have multiple parameters?
def impl(a: Int, b: Int)(f: (Int, Int) => Int): Int = f(a, b)
理想情况下,这将类似于:
Ideally, this would work something like:
impl(1, 2) { implicit (a, b) => // wrong
...
}
或者
impl(1, 2) { (implicit a, implicit b) => // also wrong
...
}
我可以使用 A => 解决这个问题.B=>C
,而是:
def impl(a: Int, b: Int)(f: Int => Int => Int): Int = f(a)(b)
impl(1, 2) { implicit a => implicit b =>
...
}
但是有没有一种方法可以在不使函数柯里化的情况下做到这一点?
But is there a way to do this without currying the functions?
应该很明显,但是 Int
在这里只是一个虚拟占位符.
It should be obvious, but Int
is just a dummy placeholder here.
推荐答案
不,这是不可能的.从部分 6.23 匿名函数规范的匿名函数语法是:
No, it's not possible. From section 6.23 Anonymous Functions of the spec, the anonymous function syntax is:
Expr ::= (Bindings | ['implicit'] id | '_') '=>' Expr
ResultExpr ::= (Bindings | (['implicit'] id | '_') ':' CompoundType) '=>' Block
Bindings ::= '(' Binding {',' Binding} ')'
Binding ::= (id | '_') [':' Type]
如您所见,implicit
case 是特殊情况,只有 1 个标识符,而重复 case Bindings
(使用重复语法 {...}
的 EBNF) 排除了使用 隐式
.
As you can see, the implicit
case is special cased to only have 1 identifier, while the repetitive case Bindings
(which uses the repetition syntax {...}
of EBNF) precludes use of implicit
.
本节中为 implicit
添加的唯一详细信息是:
The only added details for implicit
in this section are:
匿名函数的命名参数可以选择在隐式修饰符之前.在这种情况下,参数被标记为隐式;但是,参数部分本身在定义的意义上不算作隐式参数部分 此处.因此,匿名函数的参数总是必须明确给出.
A named parameter of an anonymous function may be optionally preceded by an implicit modifier. In that case the parameter is labeled implicit; however the parameter section itself does not count as an implicit parameter section in the sense defined here. Hence, arguments to anonymous functions always have to be given explicitly.
我认为这段文字还应该澄清这仅适用于单个参数(例如,具有恰好 1 个参数的匿名函数的命名参数...")
I think that this text should also clarify that this only works for a single parameter (e.g. "A named parameter of an anonymous function that has exactly 1 parameter...")
当然,最简单的解决方法是避开语法糖并将匿名函数参数重新绑定到新的隐式变量:
Of course, the simplest workaround is to eschew the syntactic sugar and rebind the anonymous function parameters to new implicit variables:
impl(a) { (b, c) =>
implicit val (impB, imbC) = (b, c)
...
}
这篇关于如何使匿名函数中的多个参数隐式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!