1. 程式人生 > 實用技巧 >通俗地解釋scala中疊加特質的構建順序和執行順序

通俗地解釋scala中疊加特質的構建順序和執行順序

  • 閒話不說,先上一段程式碼。
 1 object MixInDemo02 {
 2   def main(args: Array[String]): Unit = {
 3     val mysql4 = new MySQL4 with File4 with DB4
 4     mysql4.insert(100)
 5 
 6 //    執行結果如下
 7 //    Operate4...
 8 //    Data4
 9 //    File4
10 //    DB4
11 //    向資料庫
12 //    向檔案
13 //    插入資料 = 100
14   }
15 }
16 
17 trait Operate4 {
18 println("Operate4...") 19 def insert(id : Int) 20 } 21 22 trait Data4 extends Operate4 { 23 println("Data4") 24 override def insert(id : Int): Unit = { 25 println("插入資料 = " + id) 26 } 27 } 28 29 trait DB4 extends Data4 { 30 println("DB4") 31 override def insert(id : Int): Unit = {
32 println("向資料庫") 33 super.insert(id) 34 } 35 } 36 37 trait File4 extends Data4 { 38 println("File4") 39 override def insert(id : Int): Unit = { 40 println("向檔案") 41 super.insert(id) 42 }}
43 class MySQL4 {}
  • 解釋第3行程式碼(val mysql4 = newMySQL4 with File4 with DB4),構造mysql4物件的過程。

多特質疊加的時候,構造物件是從左往右開始。

  1. 首先執行File4的構造器,一看繼承了Data4,所以去找Data4的構造器,再看到Data4又繼承了Operate4,所以又去找Operate4的構造器。由於Operate4上面沒有超類了,所以就開始執行構造器的程式碼,println("Operate4...")。然後執行Data4的構造器程式碼,println("Data4")。最後才執行File4的構造器程式碼,println("File4")。
  2. 然後執行DB4的構造器,DB4也繼承了Data4,但是上一步Data4的構造器程式碼已經被執行過一遍了,所以這時就不會再執行了。直接執行DB4的構造器程式碼,println("DB4")。
  3. 通過以上兩步,mysql4物件就構造完畢,輸出語句的順序為:Operate4... -> Data4 ->File4 ->DB4。
  • 解釋第4行程式碼(mysql4.insert(100))的執行順序

多特質疊加的時候,執行疊加物件裡的的方法是從右往左開始。

  1. 首先執行DB4中的insert方法,即執行程式碼println("向資料庫"),然後執行程式碼super.insert(id)。
  2. 這個時候需要注意的是,這裡的super不再指的是Data4了,而是第3行程式碼(new MySQL4 with File4 with DB4)中的File4物件,因此開始執行File4中的insert方法,即println("向檔案"),然後執行super.insert(id)。
  3. 由於File4左邊已經沒有其他特質了,所以這裡的super就指的是Data4,即執行Data4中的insert方法,println("插入資料 = " + id)。
  4. 通過以上三步,insert方法就執行完畢,輸出語句的順序為:向資料庫 ->向檔案 ->插入資料 = 100。