8.3. Using a Trait Like an Abstract Class
Problem
You want to use a trait as something like an abstract class in Java.
Solution
Define methods in your trait just like regular Scala methods. In the class that extends the trait, you can override those methods or use them as they are defined in the trait.
In the following example, an implementation is provided for the
speak
method in the Pet
trait, so implementing classes don’t have
to override it. The Dog
class chooses
not to override it, whereas the Cat
class does:
trait
Pet
{
def
speak
{
println
(
"Yo"
)
}
// concrete implementation
def
comeToMaster
// abstract method
}
class
Dog
extends
Pet
{
// don't need to implement 'speak' if you don't need to
def
comeToMaster
{
(
"I'm coming!"
)
}
}
class
Cat
extends
Pet
{
// override the speak method
override
def
speak
{
(
"meow"
)
}
def
comeToMaster
{
(
"That's not gonna happen."
)
}
}
If a class extends a trait without implementing its abstract
methods, it must be defined as abstract. Because FlyingPet
does not implement comeToMaster
, it must be declared as
abstract:
abstract
class
FlyingPet
extends
Pet
{
def
fly
{
(
"I'm flying!"
)
}
}
Discussion
Although Scala has abstract classes, it’s much more common to use traits than abstract classes to implement base behavior. A class can extend only one abstract class, but it can implement multiple traits, so using traits is more flexible.
See Also
Like Java, you use
super.foo
to call a method namedfoo
in an immediate superclass. When a class mixes in multiple traits—and ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.