August 2013
Intermediate to advanced
720 pages
16h 23m
English
Rather than add a trait to an entire class, you just want to add a trait to an object instance when the object is created.
Add the trait to the object when you construct it. This is demonstrated in a simple example:
classDavidBannertraitAngry{println("You won't like me ...")}objectTestextendsApp{valhulk=newDavidBannerwithAngry}
When you compile and run this code, it will print, “You won’t like
me ...”, because the hulk object is
created when the DavidBanner class is
instantiated with the Angry trait,
which has the print statement shown in its constructor.
As a more practical matter, you might mix in something like a debugger or logging trait when constructing an object to help debug that object:
traitDebugger{deflog(message:String){// do something with message}}// no debuggervalchild=newChild// debugger added as the object is createdvalproblemChild=newProblemChildwithDebugger
This makes the log method
available to the problemChild
instance.
Read now
Unlock full access