如何定义一个以函数文字(带有隐式参数)作为参数的函数? [英] How to define a function that takes a function literal (with an implicit parameter) as an argument?

查看:124
本文介绍了如何定义一个以函数文字(带有隐式参数)作为参数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在这些行上执行某些操作(不会编译):

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.

这篇关于如何定义一个以函数文字(带有隐式参数)作为参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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