Trait in scala
Some methods can be implemented in trait.
Trait literally refers to traits or features. It is appropriate to translate them into features. Its meaning is similar to that of interfaces in java and c. However, trait supports partial implementation, that is, some methods can be implemented in scala's trait.
Next we will introduce the use of trait with a specific example.
In our example, an abstract class Aminal is defined to represent all animals, and then two trait Flyable and retriable are defined to represent flying and swimming.
Let's take a look at the implementation of Aminmal:
abstract class Animal { def walk(speed:Int) def breathe() = { println("animal breathes") }}
The abstract class Animal defines the walk Method and implements the breathe method.
Let's look at the implementation of Flyable and retriable trait:
trait Flyable { def hasFeather = true def fly } trait Swimable { def swim }
Note that there are two methods in Flyable trait. One is the hasFeather method, which has been implemented, and the other is the fly method. This method is only defined and not implemented, resumable trait only defines a swim method without specific implementation.
Next we define an animal that can fly and swim. This animal is fish e FishEagle. Let's look at the Code:
class FishEagle extends Animal with Flyable with Swimable { def walk(speed:Int) = println("fish eagle walk with speed " + speed) def swim() = println("fish eagle swim fast") def fly() = println("fish eagle fly fast") }
The FishEagle class inherits from Animal. extends Animal has two features: with, with Flyable, and with retriable.
To implement a class, you must implement the abstract class Animal walk method, or the unimplemented method defined in the two features.
The following is the main method code:
object App { def main(args : Array[String]) { val fishEagle = new FishEagle val flyable:Flyable = fishEagle flyable.fly val swimmer:Swimable = fishEagle swimmer.swim } }
In the main method, we first initialize a FishEagle object, and then use Flyable and retriable trait to call the fly and swim methods respectively. The output result is as follows:
fish eagle fly fastfish eagle swim fast
The usage of trait is like this. It is very powerful and can do anything that abstract classes can do. Its strength lies in its ability to inherit more.
The difference between trait and abstract classes is that abstract classes belong to an inheritance chain. Classes and classes do have an inheritance relationship between parent and child classes, while trait represents a feature as its name, it can be inherited.
Http://outofmemory.cn/scala/scala-trait-introduce-and-example