Scala Trait (Feature)

Scala Trait (Feature) is equivalent to Java's interface, but in fact it is more powerful than an interface.

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

In general, Scala classes can only inherit a single parent class, but when it comes to Trait (Feature), multiple traits can be inherited, which results in multiple inheritance.

A Trait (Feature) is defined in a similar way to a class, but the keyword it uses istrait, as shown below:

Example

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

The above Trait (Feature) consists of two methods:isEqualandisNotEqual. The isEqual method does not define the implementation of the method, while isNotEqual defines the implementation of the method. A subclass inheriting the trait can implement the unimplemented method. So in fact, Scala Trait (Feature) is more like Java's abstract class.

The following demonstrates a complete example of a trait:

Example

/* File name: Test.scala
* author: Example Tutorial
 * url:www.example.com
 */

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 produces the following output:

$ scalac Test.scala 
$ scala Test
false
true
true

Trait Construction Order

Traits can also have constructors, which consist of field initialization and other statements in the trait body. These statements are executed when any object that mixes in the trait is constructed.

The execution order of constructors:

  • Call the superclass constructor;
  • The trait constructor is executed after the superclass constructor and before the class constructor;
  • Traits are constructed from left to right;
  • Within each trait, the parent trait is constructed first;
  • If multiple traits share a parent trait, the parent trait will not be constructed repeatedly;
  • After all traits are constructed, the subclass is constructed.

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

Other Extensions