Scala Trait(feature)


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

Different from interfaces, it can also define the implementation of properties and methods.

Generally, a Scala class can only inherit a single parent class, but if it is a Trait (feature), it can inherit multiple ones. From the result, multiple inheritance is achieved.

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

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

The above Trait (Characteristic) consists of two It 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. Subclasses inherit traits to implement unimplemented methods. So in fact, Scala Trait (feature) is more like Java's abstract class.

The following demonstrates a complete example of the feature:

/* 文件名:Test.scala
 * author:php中文网
 * url:www.php.cn
 */
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))
   }
}

Execute the above code, the output result is:

$ scalac Test.scala 
$ scala Test
false
true
true

Feature construction sequence

Feature also There can be constructors, consisting of field initialization and other statements in the trait body. These statements will be executed during construction of any object mixed with this trait.

Execution order of constructors:

  • Call the constructor of the super class;

  • The characteristic constructor is constructed in the super class Executed after the constructor and before the class constructor;

  • Traits are constructed from left to right;

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

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

  • After all characteristics 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 type.