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 {
  import scala.io.Source
  override def details(source:String) = {
	Source.fromString(source).mkString
  }
}

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

Below image shows the execution and output in scala shell.

Scala-traits-example

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;


import scala.io.Source

trait detcar{
 def readdetails(d:String):String =
   Source.fromString(d).mkString
}


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)
 cname+"\n"+cno+"\n"+"Color:"+color
  }
}

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

Below is the output produced when we execute main method.


scala> cartest.main(null)
Alto
34
Color:Black

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.

Comments

  1. Shubham Aggarwal says:

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

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages