Easy Tutorial
❮ Scala If Else Partially Applied Functions ❯

Scala Trait

Scala Trait is equivalent to Java's interface, but it is actually more powerful than an interface.

Unlike interfaces, it can also define properties and method implementations.

Generally, a Scala class can only inherit from a single parent class, but if it is a Trait, it can inherit multiple, which results in the implementation of multiple inheritance.

The way to define a Trait is similar to a class, but the keyword used is trait, as shown below:

Example

trait Equal {
  def isEqual(x: Any): Boolean
  def isNotEqual(x: Any): Boolean = !isEqual(x)
}

The above Trait consists of two methods: isEqual and isNotEqual. The isEqual method does not define the implementation of the method, while isNotEqual defines the implementation of the method. Subclasses can implement methods that have not been implemented when they inherit traits. So in fact, Scala Trait is more like Java's abstract class.

The following demonstrates a complete example of a trait:

Example

/* Filename: Test.scala
 * author: tutorialpro.org
 * url: www.tutorialpro.org
 */
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 == x
}

object Test {
  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))
  }
}

Executing the above code, the output results are:

$ scalac Test.scala 
$ scala Test
false
true
true

Trait Construction Order

Traits can also have constructors, composed of field initialization and statements in other trait bodies. These statements are executed when any object that mixes in this trait is constructed.

The order of constructor execution is as follows:

The order of constructors is the reverse of the linearization of the class. Linearization is a technical specification that describes all supertypes of a type.

❮ Scala If Else Partially Applied Functions ❯