如何定义一个以函数文字(带有隐式参数)作为参数的函数?
我希望能够在这些行上执行某些操作(不会编译):
I want to be able to do something on these lines (won't compile):
def logScope(logger:Logger)(operation: (implicit l:Logger) => Unit) {/* code */ operation(logger) /* code */}
def operationOne(implicit logger:Logger) {/**/}
def operationTwo(implicit logger:Logger) {/**/}
然后像这样使用它:
logScope(new ConsoleLogger){logger =>
operationOne
operationTwo
}
但是我最近找到一个可行的解决方案是:
But the nearest I've come to a working solution is this:
def logScope(logger:Logger)(operation: Logger => Unit) {/* code */ operation(logger) /* code */}
def operationOne(implicit logger:Logger) {/**/}
def operationTwo(implicit logger:Logger) {/**/}
/* other code */
logScope(new ConsoleLogger){logger =>
implicit val l = logger
operationOne
operationTwo
}
我认为该语言目前尚不支持这种构造,但是仍然有任何建议或解决方法可以达到类似的结果?
I don't think the language currently allows such constructs, but still, any suggestions or workarounds to achieve similar results?
较小的更新:我已经创建了要点,上面的代码略有扩展,并带有模拟这种文字的几次尝试.到目前为止,CheatEx的版本是最好的版本.
minor update: I've created a gist with a slightly expanded version of the above code with a couple of attempts at simulating this kind of literal. As of now, CheatEx's version is the best one.
在第二个示例中,尝试以下操作:
In your second example try this:
logScope(Logger()) { implicit logger =>
operationOne
}
它应该可以正常工作.这里的逻辑是,隐式"是内部闭包中特定值的属性,而不是闭包的接口的一部分.
It should work fine. The logic here is that 'implicit' is an attribute of particular value inside closure, not a part of the closure's interface.