Scala – Traits

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

Introduction to Traits in Scala

 

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

 

class IntIterator

scala> val iterator = new IntIterator(5)

2scala> iterator.next()

scala> iterator.next()

use case 2:

scala> trait Prwatech {

     |   val name: String

     | }

trait Prwatech

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

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

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

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

scala> val course = ArrayBuffer.empty[Prwatech

4scala> course.append(DataScience)

scala> course.append(BigData)

5scala> 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

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

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

4scala> val prwa = ArrayBuffer.empty[Prwatech]

scala> prwa.append(Python)

6scala> prwa.append(Linux)

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

 

Introduction to Traits in Scala

 

Quick Support

image image