Scala高階之App特質

2021-09-08 12:25:04 字數 1816 閱讀 3041

delayedinit特質裡定義了延遲初始化方法:

def delayedinit(x: => unit): unit

然後編譯器會把這段初始化**塊裡的邏輯封裝成乙個函式物件(是(() => unit)型別)

override def delayedinit(body: => unit)

快取起來(並沒有執行),然後放到乙個集合(listbuffer)中,之後在main方法裡一行一行呼叫並執行,

所以只有在執行到main方法的時候才會觸發,從而達到延遲初始化的效果。

def main(args: array[string]) =

val c =new c

println("3. hello spark")

}}trait helper extends delayedinit

}class c extends helper

def main(args: array[string]) }

執行結果:

1. dummy text, printed before inititalization of c

2. this is the initialization code of c

3. hello spark

問題:是怎麼把封裝的初始化**塊傳給delayedinit(body: => unit)的?

, c, delayedinitbody,helper,helper

class

分別對應的是

predef..module$.println("this is the initialization code of c");

return boxedunit.unit;}

val c = new c

println(「hello spark」) }

class c extends helper

**塊封裝起來了 

最後在class helperclass裡面用publicstaticvoiddelayedinit(helper

this, function0 body) 

這就是初始化**塊的執行順序,在main方法裡呼叫delayedinit方法,先是執行 

predef..module$.println(「dummy text, printed before initialization of c」);

this.outer.c_$eq(new c());

predef..module$.println(「hello spark」);

所以是先執行 this.outer.c_$eq(new c());

new c執行時就執行語句

println(「this is the initialization code of c」)

接著執行

println(「hello spark」);

所以輸出的結果就是這樣的

dummy text, printed before initialization of c 

this is the initialization code of c

hello spark

補充內容是自己猜測的居多,不保證正確,個人覺得背後的原理其實不用深究,知道有這麼回事就行了。

scala學習之特質 trait

特質,很像j a中的介面,但是又有些不同,比如實現方法,當然j a8也可以在介面中實現乙個方法了,但是只能定義乙個default方法。當做介面使用 特質 trait logger trait consolelogger extends logger 不需要寫 overrride 在重寫 特質的抽象方...

Scala之特質構造順序(六)

簡介 和類一樣,特質也可以有構造器,由字段的初始化和其他特質體中的語句構成。構造順序 宣告類的同時混入特質 案例 object mixinseq trait aa trait bb extends aa trait cc extends bb trait dd extends bb class ee...

Scala 系列 特質 Trait

本文主要對scala中特質的概念與使用進行介紹 特質是scala裡面 復用的基礎單元。與 python 不同,python 子類可以繼承自多個父類,而 scala 不允許乙個類從從個超類繼承,只能繼承唯一的超類。但是 scala 允許乙個類混入任意數量的特質,混入就是指類使用了特質提供的方法。那麼特...