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 = ???
        }))
  • 相关阅读:
    &与&&的区别
    x^y=(x&~y)|(~x&y)证明
    a、b交换与比较
    x+y = ((x&y)<<1) + (x^y) 证明
    (x&y) + ((x^y)>>1)即x和y的算数平均值
    默认参数提升
    类型转换
    闲扯原码,补码和反码(转)
    C/C++中float和double的存储结构
    led设备驱动(s3c_led.c)
  • 原文地址:https://www.cnblogs.com/gaoxing/p/4768214.html
Copyright © 2011-2022 走看看