如何将隐式方法添加到字符串

时间:2019-04-01 12:36:38

标签: scala akka

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

以下代码可正常使用:

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
  }
}

1 个答案:

答案 0 :(得分:3)

也许是这样吗?

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
  }
}