Go Back

What is Trait in scala with example

11/22/2022
All Articles

#What is Trait in scala #example of trait #trait scala

What is Trait in scala  with example

What is Trait in scala 

 

A trait encapsulates method and field definitions,

which can then be reused by mixing them into classes.

Unlike class inheritance, in which each class must inherit from just one superclass, a class can extends in any number of traits.

Traits are used to define object types by specifying the prototype of the supported methods.

Scala also allows traits to be partially implemented but traits may not have constructor parameters.

A trait definition looks just like a class definition except that it uses the keyword trait.

The following is the basic example syntax of trait.

 

Syntax of Trait

class Scala_Tutorial extends DataCamp{
// Variables
// Methods
}

 

Below is example of  Trait in scala .

class point that is extend the trait Equal and produce the output 

 

package traitDemo

 trait Equal {

    def isEqual(x: Any): Boolean

    def isNotEqual(x: Any): Boolean = !isEqual(x)

  }

 

 

  class Point(xc: Int, yc: Int) extends Equal

{

    var x: Int = xc

    var y: Int = yc

 

    def isEqual(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == y

  }

 

  object Demo {

    def main(args: Array[String]) {

      val p1 = new Point(2, 3)

      val p2 = new Point(2, 4)

      val p3 = new Point(3, 3)

      println(p1.isNotEqual(p2))

      println(p1.isNotEqual(p3))

      println(p1.isNotEqual(2))

    }

  }

 

Below is output of our program 

trait in scala  , trait vs abstract class scala

Article