Monday, 18 December 2017

Introduction to Scala - V

We continue with more Scala on the topic of Mixins in this post. For all the work in this post, we will use Read-Evaluate-Print-Loop Scala interpreter. Some familiarity with Java will be of great help in understanding Scala. In this post, we will look at more of traits in the form of Mixins.

We have already seen Traits in this post. Mixins are traits that can be used to compose a class. The first example is very similar to the one we have seen in the earlier post:

class Class{
  def Printx(Value: Long): Unit = {
    println("Value in Class is " + Value)
  }
}

trait trait6 { def method6 }

trait trait7 extends trait6 { def method6 { println("method7 in trait7") } }

val NewClass = new Class with trait7 {
  override def Printx(Value: Long): Unit = {
  method6
  println("Value in NewClass is " + Value)
  super.Printx(Value)
  }
}


NewClass.Printx(5)

The results are shown below:

scala> class Class{
     |   def Printx(Value: Long): Unit = {
     |     println("Value in Class is " + Value)
     |   }
     | }
defined class Class

scala> trait trait6 { def method6 }
defined trait trait6

scala> trait trait7 extends trait6 { def method6 { println("method7 in trait7") } }
defined trait trait7

scala> val NewClass = new Class with trait7 {
     |   override def Printx(Value: Long): Unit = {
     |   method6
     |   println("Value in NewClass is " + Value)
     |   super.Printx(Value)
     |   }
     | }
NewClass: Class with trait7 = $anon$1@68702e03

scala> NewClass.Printx(5)
method7 in trait7
Value in NewClass is 5
Value in Class is 5


In the above example, we define a class called Class that contains a method called Printx. Next, trait6 is defined having abstract method called method6. trait7 inherits trait6 and implements method6. We then instantiate Class with Mixin trait, trait7 with keyword, with. Note that Printx is overridden with a new definition. If Printx is not overridden, NewClass would have inherited Printx as implemented in trait7. Note also that while the signature of Printx remains the same as seen from outside, internals are modified. Lastly, we call Printx and the results are in line with the definition of Printx with Mixin.

This concludes the topic Mixins.