假设我想用记录异常并继续的 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”。这(或类似的事情)可能吗?
最佳答案
事实上,它可以随心所欲地完成。其他答主很快就投降了。没有白旗!
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
关于scala - 是否可以在 Scala 中将 "this"作为隐式参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4269572/