Scala traits

A trait in Scala defines a set of features that can be implemented by classes. A trait is similar to an interface in Java.

A trait can be partially implemented, forcing the user (class) of the trait to implement the details.

For example, we can have this code:

trait Color {
    def isRed(): Boolean
}
class Red extends Color {
    def isRed() = true
}
class Blue extends Color {
    def isRed() = false
}
var red = new Red();
var blue = new Blue();
red.isRed()
blue.isRed()

The code creates a trait called Color with one partially implemented function, isRed. So, every class that uses Color will have to implement isRed().

We then implement two classes, Red and Blue, that extend the Color trait (this is the Scala syntax for using a trait). Since the isRed() function is partially implemented, both classes have to provide implementations for the trait function.

We can see how this operates in the following screenshot of the notebook display:

Scala traits

We see (in the output section at the bottom) the trait and classes created, the two instances created, and the result of calling upon the trait function for both classes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.159.10