Scala Trait (feature)

Scala Trait (feature) is equivalent to Java's interface, in fact it is more powerful than the interface.

Unlike interfaces, it also defines the implementation of properties and methods.

In general, Scala's class can only inherit a single parent class, but if it is Trait, it can inherit multiple. From the result, it realizes multiple inheritance.

Trait is defined in a similar way to a class, but it uses a trait keyword as follows:

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, and isNotEqual defines the implementation of the method. Subclass inheritance features can implement methods that are not implemented. So in fact, Scala Trait is more like the abstract class of Java.

The following demonstrates a complete example of a feature:

/* file nameļ¼šTest.scala
 * author:welookups
 * url:www.welookups.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)


> Execute the above code, the output is:

$ scalac Test.< /span>scala
$ scala Test

Characteristic construction order

Features can also have constructors, consisting of initialization of fields and statements in other features. These statements are executed when any object that is mixed into the feature is constructed.

The order in which the constructors are executed:

  • Call the constructor of the superclass;
  • The feature constructor is executed after the superclass constructor and before the class constructor;
  • Features are constructed from left to right;
  • Among each feature, the parent feature is constructed first;
  • If multiple features share a parent feature, the parent feature will not be constructed repeatedly
  • All features are constructed and subclasses are constructed.

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