Scala Trait


Release date:2023-11-21 Update date:2023-11-22 Editor:admin View counts:141

Label:

Scala Trait

Scala Trait (characteristic) is equivalent to the interface of Java, but it is actually more powerful than the interface.

Unlike an interface, it can also define the implementation of properties andmethods.

In general, the class of Scala can only inherit a single parent class, but if it is a Trait (feature), it can inherit more than one. As a result, multiple inheritance is implemented.

Trait (feature) is defined in a manner similar to that of a class, but it uses the keyword trait , as follows:

Example

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

The above Trait (characteristics) consists of two methods: isEqual and isNotEqual . isEqual method does not define the implementation of the method isNotEqual the implementation of the method is defined. Subclass inheritance features can implement methods that have not been implemented. So Scala Trait is actually more like an abstract class of Java.

The following demonstrates a complete example of a feature:

Example

/* file name:Test.scala
 * author:Novice Tutorial
 * url:www.runoob.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))
   }
}

Execute the above code, and the output is as follows:

$ scalac Test.scala
$ scala Test
false
true
true

Feature construction sequence

Features can also have constructors, which are made up of initialization of fields and statements in other features. These statements are executed when any object mixed with the feature is constructed.

The execution order of the constructor:

  • Call the constructor of the superclass

  • The feature constructor executes after the superclass constructor and beforethe class constructor

  • Features are constructed from left to right

  • Of each feature, the parent feature is constructed first

  • If multiple features share a parent feature, the parent feature will not be reconstructed

  • All features are constructed and subclasses are constructed.

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

Powered by TorCMS (https://github.com/bukun/TorCMS).