Latest web development tutorials

Scala Trait (feature)

Scala Trait (characteristics) equivalent Java interface, in fact, it is powerful than the interface also.

The interface is different, it can achieve the definition of the properties and methods.

Under normal circumstances Scala class can only inherit a single parent, but if Trait (feature), then you can inherit multiple, from the results is to implement multiple inheritance.

Information Trait (feature) is similar to the definition of the class, but it uses the keywordtrait, as follows:

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

Above Trait (characteristic) composed by twomethods: isEqual and isNotEqual.isEqual method is not implementation-defined method, it isNotEqual define the methods of. Subclasses inherit the features can be implemented method is not implemented. So in fact Scala Trait (feature) like Java abstract class.

The following examples demonstrate the complete features:

/* 文件名:Test.scala
 * author:本教程
 * url:www.w3big.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))
   }
}

Implementation of the above code, the output is:

$ scalac Test.scala 
$ scala Test
false
true
true

Characteristics of construction order

Feature can also have constructors, and other features of the body by the initialization field's statements constituted. These statements at any objects mixed into the structure is characterized in will be executed.

The execution order of the constructor:

  • Call the constructor of the superclass;
  • Characterized constructor after the superclass constructor, before the class constructor execution;
  • Trait is configured from left to right;
  • Each feature among the parent trait was first constructed;
  • If there are multiple features a parent characteristics, parent trait will not be repeated structure
  • All features are configured finished subclass is constructed.

Constructor is a linear sequence of reverse class. Linearization is to describe a type of all types of super-kind technical specifications.