Scala Trait Mixin order -


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 doubleit addit     obj.printit()    }  } //output : adding doubling 4 8 12 16 

in above code, price() method addit trait executes first (from print statement).but shouldn't value 6 10 14 18? why values doubled before adding?

your traits stacked in order declare them:

addit

doubleit

numbers

when run printit, you're doing on addit, resulting in following call chain:

addit.printit addit.printit.price       //here print "adding" addit.price.super.price   //calls doubleit's price doubleit.price            //here print "doubling" doubleit.super.price      //calls number's price numbers.price             //returns list(1, 3, 5, 7) doubleit.super.price.map  //doubles list input addit.super.price.map     //adds 2 result addit.printit.foreach     //prints final result 

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -