2016-09-22 69 views
0
object sandbox { 

    class Numbers { 
    def price() : List[Int] = List(1,3,5,7) 
    def printIt(): Unit = { 
     price.foreach(x => print(x+ " ")) 
    } 
    } 

    trait DoubleIt extends Numbers { 
    override def price() : List[Int] ={ 
     println("doubling") 
     super.price.map(x => x*2) 
    } 
    } 

    trait AddIt extends Numbers { 
    override def price() : List[Int] = { 
     println("adding") 
     super.price.map(x => x+2) 
    } 
    } 

    def main(args :Array[String]): Unit = { 
    val obj = new Numbers with DoubleIt with AddIt 
    obj.printIt() 
    } 

} 
//output : 
adding 
doubling 
4 8 12 16 

在上面的代碼,從AddIt性狀price()方法執行第一(從打印語句)。但不應值是6 10 14 18?爲什麼在添加之前數值會增加一倍?Scala的性狀密新訂購

回答

4

你性狀堆疊的順序來聲明他們:

ADDIT

DoubleIt

當你運行爲printit,你這樣做是對的ADDIT,導致在以下呼叫鏈中:

AddIt.printIt 
AddIt.printIt.price  //here you get to print "adding" 
AddIt.price.super.price //calls DoubleIt's price 
DoubleIt.price   //here you get to print "doubling" 
DoubleIt.super.price  //calls Number's price 
Numbers.price    //returns List(1, 3, 5, 7) 
DoubleIt.super.price.map //doubles your list input 
AddIt.super.price.map  //adds 2 to the result 
AddIt.printIt.foreach  //prints the final result 
5

結果是有意義的:

  1. printIt呼叫AddIt.price
  2. AddIt.price呼叫DoubleIt.price,和然後增加2至每一個
  3. DoubleIt.price呼叫Numbers.price,然後dubles每一個,返回List(2,6,10,14)
  4. 這意味着AddIt.price返回List(2+2, 6+2, 10+2, 14+2),這的確是打印結果

這裏的關鍵是理解的是DoubleIt.price確實AddIt.price開始之前,但它使用的DoubleIt.price結果創造的返回值,加法之前。