MOCKSTACKS
EN
Questions And Answers

More Tutorials









Scala Traits

Examples

Stackable Modification with Traits


You can use traits to modify methods of a class, using traits in stackable fashion.

The following example shows how traits can be stacked. The ordering of the traits are important. Using different order of traits, different behavior is achieved.

class Ball {
 def roll(ball : String) = println("Rolling : " + ball)
}
trait Red extends Ball {
 override def roll(ball : String) = super.roll("Red-" + ball)
}
trait Green extends Ball {
 override def roll(ball : String) = super.roll("Green-" + ball)
}
trait Shiny extends Ball {
 override def roll(ball : String) = super.roll("Shiny-" + ball)
}
object Balls {
 def main(args: Array[String]) {
 val ball1 = new Ball with Shiny with Red
 ball1.roll("Ball-1") // Rolling : Shiny-Red-Ball-1
 val ball2 = new Ball with Green with Shiny
 ball2.roll("Ball-2") // Rolling : Green-Shiny-Ball-2
 }
}

Note that super is used to invoke roll() method in both the traits. Only in this way we can achieve stackable modification. In cases of stackable modification, method invocation order is determined by linearization rule.

Trait Basics


This is the most basic version of a trait in Scala.

trait Identifiable {
 def getIdentifier: String
 def printIndentification(): Unit = println(getIdentifier)
}
case class Puppy(id: String, name: String) extends Identifiable {
 def getIdentifier: String = s"$name has id $id"
}

Since no super class is declared for trait Identifiable, by default it extends from AnyRef class. Because no definition for getIdentifier is provided in Identifiable, the Puppy class must implement it. However, Puppy inherits the implementation of printIdentification from Identifiable.

In the REPL:

val p = new Puppy("K9", "Rex")
p.getIdentifier // res0: String = Rex has id K9
p.printIndentification() // Rex has id K9



Conclusion

In this page (written and validated by ) you learned about Scala Traits . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala Tuples.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.