是否可以通过"this"?作为Scala中的隐式参数? [英] Is it possible to pass "this" as implicit parameter in Scala?
问题描述
假设我想用可以记录异常并继续执行的try-catch块包装可以引发异常的代码.像这样:
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
}
理想情况下,我想用于记录在调用对象上定义的Logger(如果有)(如果没有,则得到编译时错误).我很想定义这样的东西:
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)
}
}
其中objectWithLogger将以某种方式神奇地"在客户端代码中扩展为"this".这(或类似的东西)有可能吗?
where objectWithLogger would somehow "magically" expand to "this" in client code. Is this (or a similar thing) possible?
推荐答案
实际上,它可以随您所愿进行.其他答复者投降得太快.没有白旗!
It can in fact be done just as you want. The other answerers surrendered too quickly. No white flags!
package object foo {
type HasLogger = { def logger: Logger }
implicit def mkLog(x: HasLogger) = new {
def loggingExceptions(body: => Unit): Unit =
try body
catch { case ex: Exception => println(ex) }
}
}
package foo {
case class Logger(name: String) { }
// Doesn't compile:
// class A {
// def f = this.loggingExceptions(println("hi"))
// }
// 1124.scala:14: error: value loggingExceptions is not a member of foo.A
// def f = this.loggingExceptions(println("hi"))
// ^
// one error found
// Does compile
class B {
def logger = Logger("B")
def f = this.loggingExceptions(println("hi"))
def g = this.loggingExceptions(throw new Exception)
}
}
object Test {
def main(args: Array[String]): Unit = {
val b = new foo.B
b.f
b.g
}
}
// output
//
// % scala Test
// hi
// java.lang.Exception
这篇关于是否可以通过"this"?作为Scala中的隐式参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!