English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Scala Traits

Scala Traits are equivalent to Java interfaces, and actually they are more powerful than interfaces.

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

Generally, Scala classes can only inherit a single superclass, but if it is a Trait, it can inherit multiple ones, which results in multiple inheritance.

The way Traits are defined is similar to classes, but it uses the keyword traitas shown below:

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

The above trait consists of two methods:isEqual and isNotEqualThe isEqual method does not define the method implementation, while isNotEqual defines the method implementation. Subclasses inheriting the trait can implement the unimplemented methods. Therefore, Scala Traits are more similar to Java's abstract classes.

The following demonstrates a complete example of the feature:

/* Filename: Test.scala
 * author: Basic Tutorial Website
 * url:www.oldtoolbag.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))
   }
}

When the above code is executed, the output is:

$ scalac Test.scala 
$ scala Test
false
true
true

Trait construction order

Traits can also have constructors, which are composed of field initialization and statements in other trait bodies. These statements are executed when any object mixed with the trait is constructed.

The execution order of constructors:

  • Call the super class constructor;

  • Trait constructors are executed after the super class constructor and before the class constructor;

  • Traits are constructed from left to right;

  • In each trait, the parent trait is constructed first;

  • If multiple traits share a parent trait, the parent trait will not be constructed repeatedly.

  • All traits are constructed, and subclasses are constructed.

The order of constructors is the reverse of the class linearization. Linearization is a specification technique that describes all super types of a type.