zoukankan      html  css  js  c++  java
  • 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 = ???
        }))
  • 相关阅读:
    虚拟机virtualBox
    在scala命令行中加入类库
    使用git submodule
    Julia1.x安装
    texshop 使用技巧
    vimdiff换行
    双系统磁盘挂载失败
    www.wolframalpha.com
    sublime3激活方法
    实验数据
  • 原文地址:https://www.cnblogs.com/gaoxing/p/4768214.html
Copyright © 2011-2022 走看看