Home » Scala language

Traits in Scala

Scala traits: In this tutorial of Scala traits, we will discuss traits, their implementation and working example.
Submitted by Shivang Yadav, on July 15, 2019

Scala traits

Traits in Scala are like interfaces in Java. A trait can have fields and methods as members, these members can be abstract and non-abstract while creation of trait.

The implementation of Scala traits can implement a trait in a Scala Class or Object.

Some features of Scala traits:

  • Members can be abstract as well as concrete members.
  • A trait can be extended by another trait.
  • Made using "trait" keyword.


    trait trait_name{
	    def method()

Example showing the use of trait

This example is taken from https://docs.scala-lang.org/tour/traits.html

trait Iterator[A] {
  def hasNext: Boolean
  def next(): A
class IntIterator(to: Int) extends Iterator[Int] {
  private var current = 0
  override def hasNext: Boolean = current < to
  override def next(): Int = {
    if (hasNext) {
      val t = current
      current += 1
    } else 0
val iterator = new IntIterator(10)
iterator.next()  // returns 0
iterator.next()  // returns 1

This example shows the use of trait and how it is inherited? The code creates a trait name Iterator, this trait there are 2 abstract methods hasNext and next. Both the methods are defined in the class IntInterator which defines the logic. And then creates objects for this class to use the trait function.

Another working example,

trait hello{
    def greeting();

class Ihelp extends hello {
    def greeting() {
        println("Hello! This is include Help! ");

object MyClass {
    def main(args: Array[String]) {
        var v1 = new Ihelp();


Hello! This is include Help! 

This code prints "Hello! This is include Help!" using trait function redefinition and then calling that function.

Some pros and cons about using traits

  • Traits are a new concept in Scala so they have limited usage and less interoperability. So, for a Scala code That can be used with a Java code should not use traits. The abstract class would be a better option.
  • Traits can be used when the feature is to be used in multiple classes, you can use traits with other classes too.
  • If a member is to be used only once then the concrete class should be used rather than a Traits it improves the efficiency of the code and makes it more reliable.

All Scala Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.