Scala – Traits

  • date 29th December, 2020 |
  • by Prwatech |
  • 0 Comments

Traits in Scala is same as interfaces in Java. But traits are more powerful than the interface in Java because traits permits to allow members implementation. Traits can have methods(abstract and non-abstract both), and fields as its individuals.

use case 1:

scala> trait PrwatechIterator[X] {

        def hasNext: Boolean

        def next(): X

     }

trait PrwatechIterator

scala> class IntIterator(to: Int) extends PrwatechIterator[Int] {

        private var current = 1

        override def hasNext: Boolean = current < to

        override def next(): Int = {

          if (hasNext) {

            val t = current

            current += 2

            t

          } else 0

        }

     }

class IntIterator

scala> val iterator = new IntIterator(5)

scala> iterator.next()

scala> iterator.next()

use case 2:

scala> trait Prwatech {

     |   val name: String

     | }

trait Prwatech

scala> class BigData(val name: String) extends Prwatech

scala> class DataScience(val name: String) extends Prwatech

scala> val DataScience = new DataScience("MachineLearning")

scala> val BigData = new BigData("Hadoop")

scala> val course = ArrayBuffer.empty[Prwatech

scala> course.append(DataScience)

scala> course.append(BigData)

scala> course.foreach(Prwatech => println(Prwatech.name))

use case 3:

scala> trait Prwatech {

     |   val name: String

     | }

trait Prwatech

scala> class Linux(val name: String) extends Prwatech

scala> class Python(val name: String) extends Prwatech

scala> val Python = new Python("Programming Language")

scala> val Linux = new Linux("Operating System")

scala> val prwa = ArrayBuffer.empty[Prwatech]

scala> prwa.append(Python)

scala> prwa.append(Linux)

scala> prwa.foreach(Prwatech => println(Prwatech.name))

Quick Support

image image