Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Scala Trait

Scala Trait

Scala Trait is equivalent to a Java interface, but in fact it is even more powerful than an interface.

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

In general, a Scala class can inherit from only a single parent class, but with a Trait it can inherit from multiple ones, effectively achieving multiple inheritance.

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

Example

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 has no implementation defined, while isNotEqual defines the implementation. A subclass inheriting the trait can implement the unimplemented method. So in fact a Scala Trait is more like a Java abstract class.

The following demonstrates a complete example of a trait:

Example

/* Filename: Test.scala
 * author:Runoob 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

)

)

   

}

}

The output of the code above is:



$ scalac Test.scala 

$ scala Test

false

true

true


Trait construction order

Traits can also have constructors, consisting of field initializations and statements in the trait body. These statements are executed whenever an object that mixes in the trait is constructed.

The order of constructor execution:

The order of constructors is the reverse of the class's linearization. Linearization is a technical specification describing all supertypes of a type.