HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
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.w3resource.net */ 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
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:
Constructor is a linear sequence of reverse class. Linearization is to describe a type of all types of super-kind technical specifications.