如何创建具有多个隐式参数的 Scala 匿名函数 [英] How do you create scala anonymous function with multiple implicit parameters
问题描述
我有名为run1"和run2"的 Scala 函数,它们接受 3 个参数.当我应用它们时,我想提供一个带有隐式参数的匿名函数.在下面的示例代码中,这两种情况都不起作用.我想知道
- 这可能吗?
- 如果可能,语法是什么?
<预><代码>对象主扩展应用程序{type fType = (Object, String, Long) => Objectdef run1( f: fType ) {f(新对象,第二个参数",3)}run1 { 隐式 (p1, p2, p3) =>//失败打印(p1)打印(p2)打印(p3)新对象()}def run2( f: fType ) {val fC = f.curredfC(new Object)("第二个参数")(3)}run2 { 隐式 p1 => 隐式 p2 => 隐式 p3 =>//失败打印(p1)打印(p2)打印(p3)新对象()}}
你在 run2
中柯里化了函数,所以 run2
仍然需要一个非柯里化的函数.请参阅下面的代码以了解有效的版本:
object Main 扩展 App {type fType = (Object, String, Long) =>目的类型 fType2 = 对象 =>字符串 =>长 =>对象//柯里化def run1( f: fType ) {f(新对象,第二个参数",3)}//不起作用,语言规范不允许run1 { 隐式 (p1, p2, p3) =>打印(p1)打印(p2)打印(p3)新对象()}def run2( f: fType2 ) {f(new Object)("第二个参数")(3)}run2 { 隐式 p1 =>隐式 p2 =>隐式 p3 =>打印(p1)打印(p2)打印(p3)新对象()}}
I have scala functions called "run1" and "run2" which accept 3 parameters. When I apply them I want to provide an anonymous function with implicit parameters. It doesn't work in both cases in example codes below. I want to know if
- Is that even possible?
- If it is possible, what's the syntax?
object Main extends App {
type fType = (Object, String, Long) => Object
def run1( f: fType ) {
f( new Object, "Second Param", 3)
}
run1 { implicit (p1, p2, p3) => // fails
println(p1)
println(p2)
println(p3)
new Object()
}
def run2( f: fType ) {
val fC = f.curried
fC(new Object)("Second Param")(3)
}
run2 { implicit p1 => implicit p2 => implicit p3 => // fails
println(p1)
println(p2)
println(p3)
new Object()
}
}
You're currying the function inside run2
so run2
still needs a non-curried function. See the code below for a version that works:
object Main extends App {
type fType = (Object, String, Long) => Object
type fType2 = Object => String => Long => Object //curried
def run1( f: fType ) {
f( new Object, "Second Param", 3)
}
// Won't work, language spec doesn't allow it
run1 { implicit (p1, p2, p3) =>
println(p1)
println(p2)
println(p3)
new Object()
}
def run2( f: fType2 ) {
f(new Object)("Second Param")(3)
}
run2 { implicit p1 => implicit p2 => implicit p3 =>
println(p1)
println(p2)
println(p3)
new Object()
}
}
这篇关于如何创建具有多个隐式参数的 Scala 匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!