Scala Traits Example Tutorial

Filed Under: Scala

Scala Traits consists of method and field definitions that can be reused by mixing classes. The class can mix any number of traits.

  • Traits define the objects by specifying the signature of the supported methods.
  • Traits are declared in the same way as class except that the keyword trait is used.

For example consider a trait without any method implementation below.

trait Cardetails{
	def details(d:String):String

class Cardet extends Cardetails {
  override def details(source:String) = {

object car {
  def main(args:Array[String]){
	val c1 = new Cardet
	println(c1.details("Car details are being displayed"))

Below image shows the execution and output in scala shell.


We are defining a trait Cardetails without any method implementation. In the class Cardet we are overriding the method details and then creating an object car.

Consider an example for a trait with method implementation;


trait detcar{
 def readdetails(d:String):String =

class Car(var cname:String, var cno:Int){
  def details = cname+" "+cno

class Alto( cname:String, cno:Int,var color:String) extends Car(cname,cno) with detcar{
  override def details = {
 val det = readdetails(color)

object cartest {
  def main(args:Array[String]){
 val a1 = new Alto("Alto",34,"Black")

Below is the output produced when we execute main method.

scala> cartest.main(null)

We are defining the trait cardet with the method “readdetails” having the implementation. In the class car we are defining “details” with cname and cno. We are declaring the class Alto which extends car class and implements the trait cardet with an extra information about car color. We are creating cartest object and invoking the Alto class passing the name number and color and printing the details.

Usage of Traits

While implementing a reusable collection or behavior, we have to decide between a trait and abstract class. There are some of the guidelines that can be followed.

  1. If efficiency is the key criteria then it is advisable to use class. Traits get compiled to interfaces and therefore may pay a slight performance overhead.
  2. If you need to inherit from java code then better use abstract classes as traits do not have Java analog it would be strange to inherit from a trait.
  3. Concrete class would be recommended if the behavior is not reusable.
  4. Trait can be used if the behavior is reused in multiple, unrelated classes.

That’s all for a quick roundup on Scala traits, we will look into more scala features in coming posts.


  1. Shubham Aggarwal says:

    Traits look like interfaces from Java 9. Do you have a lesson for comparing the two?

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content