Extending traits

In order to extend traits or classes, you need to use the extend keyword. Traits cannot be instantiated because it may contain unimplemented methods. So, it's necessary to implement the abstract members in the trait:

trait Cat extends Animal{ }

A value class is not allowed to extend traits. To permit value classes to extend traits, universal traits are introduced, which extends for Any. For example, suppose that we have the following trait defined:

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

Now, to extend the preceding trait in Scala using the universal trait, we follow the following code segment:

trait EqualityPrinter extends Any {
def print(): Unit = println(this)
}

So, what is the difference between an abstract class and the traits in Scala? As you have seen, an abstract class can have constructor parameters, type parameters, and multiple parameters. However, a trait in Scala can have only type parameters.

A trait is fully interoperable if, and only if, it does not contain any implementation code. Furthermore, Scala traits are fully interoperable with Java interfaces in Scala 2.12. Because Java 8 allows method implementations in its interfaces, too.

There might be other cases for traits as well, for example, an abstract class can extend a trait or, if needed, any normal class (including the case classes) can extend an existing trait. For example, an abstract class can also extend traits:

abstract class Cat extends Animal { }

Lastly, a normal Scala class also can extend a Scala trait. Since classes are concrete, (that is, instances can be created), the abstract members of the trait should be implemented. In the next section, we will discuss the Java interoperability of Scala codes. Now let's peep into another important concept in every OOP, called abstract classes. We will discuss this in the next section.

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

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