Traits
Summary :
- They are similar to interfaces in java
- They cannot be instantiated
- Unlike Java they can have methods.
- Instances of objects can extend trait
- Uses "with" or "extends keyword
Usages :
- Wherever usability is a priority
- When there is no IS-A relation ship ie., unrelated classes
- When the class under cnsideration already has extended another class (this is very rare as this is usually a design flaw.
Note : Trait can also extend an object instance .
UseCase:
trait Debugger { def log(message: String) {
do something with message
}}
val problemChild = new ProblemChild ()with Debugger
Example :
object testing extends App{
val obj1:SomeClass=new SomeClass() //
val x = new newClass() with Trait1 //Object instance extending a trait
println(x.Tvar1)
println(x.Cvar3)
}
//-------------------
class SomeClass extends newClass with Trait1 with Trait2 {
println(Tvar1)
println(Tvar2)
println(Cvar3)
}
trait Trait1{
val Tvar1="trait1"}
trait Trait2{
val Tvar2="trait2"}
class newClass(){
val Cvar3="class"}
Result :
trait1 trait2 class trait1 class