gpt4 book ai didi

scala - 如何向字符串添加隐式方法

转载 作者:行者123 更新时间:2023-12-02 20:02:51 25 4
gpt4 key购买 nike

如何将隐式方法写入字符串以直接记录日志。

下面的代码工作正常:

case class Worker(name: String) extends Actor with ActorLogging {
override def receive: Receive = {
case string: String => log.info("string received")
case _ => log.info("unknown message received")
}
}

想要将 .log 隐式方法添加到字符串中,它应该调用 log.info("message") ,如下所示:

case class Worker(name: String) extends Actor with ActorLogging {
override def receive: Receive = {
case string: String => "string received".log
case _ => "unknown message received".log
}
}

最佳答案

也许是这样的?

trait LoggableString {this: ActorLogging =>

private val logger = log //since there's name collision, we need to capture log method

implicit class RichString(s: String) {
def log() = logger.info(s)
}

}

class MyActor extends Actor with ActorLogging with LoggableString {

override def receive: Receive = {
case msg => "Hello".log
}
}

或者 Alexey Romanov 建议的另一个解决方案:

trait ExtendedActorLogging extends ActorLogging {this: Actor =>

private val logger = log

implicit class RichString(s: String) {
def log() = logger.info(s)
}

}

class MyActor extends Actor with ExtendedActorLogging {

override def receive: Receive = {
case msg => "Hello".log
}
}

关于scala - 如何向字符串添加隐式方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55455300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com