码迷,mamicode.com
首页 > 其他好文 > 详细

scala中的self type

时间:2015-08-29 00:47:29      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

 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 = ???
    }))

 

scala中的self type

标签:

原文地址:http://www.cnblogs.com/gaoxing/p/4768214.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!