Saturday, February 1, 2020

scala : Traits

Traits


Summary :

  1. They are similar to interfaces in java
  2. They cannot be instantiated
  3. Unlike Java they can have methods.
  4. Instances of objects can extend trait
  5. Uses "with" or "extends keyword

Usages :

  1. Wherever usability is a priority
  2. When there is no IS-A relation ship ie., unrelated classes
  3. 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