8.5. Limiting Which Classes Can Use a Trait by Inheritance

Problem

You want to limit a trait so it can only be added to classes that extend a superclass or another trait.

Solution

Use the following syntax to declare a trait named TraitName, where TraitName can only be mixed into classes that extend a type named SuperThing, where SuperThing may be a trait, class, or abstract class:

trait [TraitName] extends [SuperThing]

For instance, in the following example, Starship and StarfleetWarpCore both extend the common superclass StarfleetComponent, so the StarfleetWarpCore trait can be mixed into the Starship class:

class StarfleetComponent
trait StarfleetWarpCore extends StarfleetComponent
class Starship extends StarfleetComponent with StarfleetWarpCore

However, in the following example, the Warbird class can’t extend the StarfleetWarpCore trait, because Warbird and StarfleetWarpCore don’t share the same superclass:

class StarfleetComponent
trait StarfleetWarpCore extends StarfleetComponent
class RomulanStuff

// won't compile
class Warbird extends RomulanStuff with StarfleetWarpCore

Attempting to compile this second example yields this error:

error: illegal inheritance; superclass RomulanStuff
 is not a subclass of the superclass StarfleetComponent
 of the mixin trait StarfleetWarpCore
class Warbird extends RomulanStuff with StarfleetWarpCore
                                        ^

Discussion

A trait inheriting from a class is not a common occurrence, and in general, Recipes 8.6 and Recipe 8.7 are more commonly used to limit the classes ...

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.