第27课:Scala面向对象内幕实践解密

1.App类的代码
延迟初始化,就是一开始的时候只是造了个对象出来,但是类的属性并没有填充上,当你需要用的时候,才会填充上,才真正完成实例化
DelayedInit也是实现了类似的功能
App类的注释非常精彩:

/** The `App` trait can be used to quickly turn objects
 *  into executable programs. Here is an example:
 *  {{{
 *  object Main extends App {
 *    Console.println("Hello World: " + (args mkString ", "))
 *  }
 *  }}}
 *  Here, object `Main` inherits the `main` method of `App`.
 *
 *  `args` returns the current command line arguments as an array.
 *
 *  ==Caveats==
 *
 *  '''''It should be noted that this trait is implemented using the [[DelayedInit]]
 *  functionality, which means that fields of the object will not have been initialized
 *  before the main method has been executed.'''''
 *
 *  It should also be noted that the `main` method will not normally need to be overridden:
 *  the purpose is to turn the whole class body into the “main method”. You should only
 *  chose to override it if you know what you are doing.
 *
 *  @author  Martin Odersky
 *  @version 2.1, 15/02/2011
 */
trait App extends DelayedInit {
protected def args: Array[String] = _args

private var _args: Array[String] = _

 private val initCode = new ListBuffer[() => Unit]

private val initCode = new ListBuffer[() => Unit]

//因为所有的main方法返回值的都是Unit,所以这里返回值是Unit

/** The init hook. This saves all initialization code for execution within `main`.
   *  This method is normally never called directly from user code.
   *  Instead it is called as compiler-generated code for those classes and objects
   *  (but not traits) that inherit from the `DelayedInit` trait and that do not
   *  themselves define a `delayedInit` method.
   *  @param body the initialization code to be stored for later execution
   */
  override def delayedInit(body: => Unit) {
    initCode += (() => body)
  }

  /** The main method.
   *  This stores all argument so that they can be retrieved with `args`
   *  and the executes all initialization code segments in the order they were
   *  passed to `delayedInit`
   *  @param args the arguments passed to the main method
   */
  def main(args: Array[String]) = {
    this._args = args
    for (proc <- initCode) proc()
    if (util.Properties.propIsSet("scala.time")) {
      val total = currentTime - executionStart
      Console.println("[total " + total + "ms]")
    }
  }

那在哪里能看到把body代码加进去initCode的呢?
可以看到接口:

/** Classes and objects (but note, not traits) inheriting the `DelayedInit` 
 *  marker trait will have their initialization code rewritten as follows:
 *  `code` becomes `delayedInit(code)`.
 *
 *  Initialization code comprises all statements and all value definitions
 *  that are executed during initialization.
 *
 *  Example:
 *  {{{
 *    trait Helper extends DelayedInit {
 *      def delayedInit(body: => Unit) = {
 *        println("dummy text, printed before initialization of C")
 *        body // evaluates the initialization code of C
 *      }
 *    }
 *
 *    class C extends Helper {
 *      println("this is the initialization code of C")
 *    }
 *
 *    object Test extends App {
 *      val c = new C
 *    }
 *  }}}
 *  
 *  Should result in the following being printed:
 *  {{{
 *    dummy text, printed before initialization of C
 *    this is the initialization code of C
 *  }}}
 *
 *  @see "Delayed Initialization" subsection of the Scala Language Specification (section 5.1)
 *
 *  @author  Martin Odersky
 */
trait DelayedInit {
  def delayedInit(x: => Unit): Unit
}

注释非常精彩,假如改成:

val c=new C()

println("end...")

end...在最后才打印出来,所以delayedInit究竟是怎么传进去的?什么时候传进去的?

看一个例子:

trait Helper extends DelayedInit {
  override def delayedInit(body: => Unit): Unit = {
    println("dummy text, printed before initialization of C")
    body
  }
}

class C extends Helper{
  println("this is the initialization code of C")
}

object AppInternals extends App {

    val c=new C()

    println("end...")

}

反编译C$delayedInit$body.class:

![)8_]{U(FT))YP810K3)UA0N.png](http://upload-images.jianshu.io/upload_images/2735954-691b5d5df5efdfe6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

其实是这样的:在编译的时候,会把代码赋值给body,
然后在执行的时候,main方法会调用delayInit(),把body传进去,才真正地进行初始化

延迟初始化是不是适用于任何情况呢?
肯定不是的,假如一个类要依赖于另外一个类的业务逻辑的时候,这时候一般就不行了

归纳总结:1.关于延迟初始化
2.关于App类
3.看例子以及理解背后的原理
4.延迟初始化适用于所有情况吗?

cccc.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,568评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,612评论 4 59
  • 窗外白色的篱笆,脚下开着几朵花,好像美丽的图画,那是我的家。——魏晨《写给我的家》 我家没有白色篱笆,墙角下也未曾...
    雪KiVi阅读 516评论 0 1
  • 迷茫的日子心找不到方向 心中有一座圣山 却不知向何方朝圣 有人走着 有人停下 走着的希冀离圣山更近 停下的希冀找明...
    月下纵横阅读 300评论 0 1