是否可以通过“this”?作为 Scala 中的隐式参数?
假设我想用一个记录异常并继续的 try-catch 块来包装可以引发异常的代码。类似的:
loggingExceptions {
// something dangerous
}
理想情况下,我想用于记录调用对象上定义的 Logger(如果有的话)(如果没有,则会出现编译时错误)。我很想定义这样的东西:
def loggingExceptions[L <: { def logger: Logger }](work: => Unit)(implicit objectWithLogger: L): Unit = {
try {
work
} catch {
case t: Exception => objectWithLogger.logger.error(t.getMessage)
}
}
其中 objectWithLogger 会以某种方式“神奇地”扩展到客户端代码中的“this”。这(或类似的事情)可能吗?
Suppose I want to wrap code that can throw exceptions with a try-catch block that logs the exception and continues. Something like:
loggingExceptions {
// something dangerous
}
Ideally, I would like to use for logging the Logger defined on the calling object, if any (and if none, get a compile-time error). I'd love to define something like this:
def loggingExceptions[L <: { def logger: Logger }](work: => Unit)(implicit objectWithLogger: L): Unit = {
try {
work
} catch {
case t: Exception => objectWithLogger.logger.error(t.getMessage)
}
}
where objectWithLogger would somehow "magically" expand to "this" in client code. Is this (or a similar thing) possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
事实上它可以按照你想要的方式完成。其他回答者太快投降了。没有白旗!
It can in fact be done just as you want. The other answerers surrendered too quickly. No white flags!
Debilski 的回答会起作用,但我不确定我是否看到在这里使用结构类型(即
{ def logger: Logger }
)的充分理由。每当调用logger
时,这样做都会产生额外的运行时开销,因为结构类型的实现依赖于反射。loggingExceptions
方法与日志记录密切相关,因此我只需将其作为 Logging 特征的一部分即可:Debilski's answer will work, but I'm not sure I see a good reason to use a structural type (i.e.
{ def logger: Logger }
) here. Doing so will incur extra runtime overhead wheneverlogger
is invoked, since the implementation of structural types relies on reflection. TheloggingExceptions
method is closely tied to logging, so I would just make it part of a Logging trait:您可以向所有想要使用
defloggingExceptions
的类添加一个特征,并在这个特征中添加一个期望def logger: Logger
可用的自我类型。You could add a trait to all classes which want to use
def loggingExceptions
and in this trait add a self-type which expectsdef logger: Logger
being available.