×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Traits in Scala

By IncludeHelp Last updated : October 22, 2024

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.

Syntax

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
      t
    } else {
      throw new NoSuchElementException("No more elements in the iterator")
    }
  }
}

val iterator = new IntIterator(10)
println(iterator.next())  // returns 0
println(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(): Unit
}

class IHelp extends Hello {
  def greeting(): Unit = {
    println("Hello! This is Help!")
  }
}

object MyClass {
  def main(args: Array[String]): Unit = {
    val v1 = new IHelp()
    v1.greeting()
  }
}

Output

Hello! This is include Help! 

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

Pros and Cons

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.

Comments and Discussions!

Load comments ↻





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