scala中的self type

 scala目前的书籍有两《快学scala》和《scala编程》。资料确实不多,对这个语法使用只能结合使用进行理解。

先看源码:

private[spark] trait ActorLogReceive {
  self: Actor =>

  override def receive: Actor.Receive = new Actor.Receive {

    private val _receiveWithLogging = receiveWithLogging

    override def isDefinedAt(o: Any): Boolean = {
      val handled = _receiveWithLogging.isDefinedAt(o)
      if (!handled) {
        log.debug(s"Received unexpected actor system event: $o")
      }
      handled
    }

    override def apply(o: Any): Unit = {
      if (log.isDebugEnabled) {
        log.debug(s"[actor] received message $o from ${self.sender}")
      }
      val start = System.nanoTime
      _receiveWithLogging.apply(o)
      val timeTaken = (System.nanoTime - start).toDouble / 1000000
      if (log.isDebugEnabled) {
        log.debug(s"[actor] handled message ($timeTaken ms) $o from ${self.sender}")
      }
    }
  }

  def receiveWithLogging: Actor.Receive

  protected def log: Logger
}

这块代码是spark的akka日志记录代码,很具有代表性,self:Actor =>这里有两个作用

1: ActorLogReceive的实现类必须继承Actor

2: 重写Actor里面的方法,该trait里面使用Actor里面的属性不要添加self.  

本理实现一种代理,或是模板模式.... 

来看看他的使用

    lazy val actorRef = actorSystem.actorOf(Props(new Actor with ActorLogReceive with Logging{
      override def receiveWithLogging: Receive = ???
    }))

 

posted @ 2015-08-29 00:10  高兴的博客  阅读(1520)  评论(0编辑  收藏  举报