mix in

How to declare that a Scala trait can only be mixed into a type that has a specific method

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 8.7, “How to declare that a Scala trait can only be mixed into a type that has a specific method.”

Problem

You only want to allow a trait to be mixed into a type (class, abstract class, or trait) that has a method with a given signature.

Solution

Use a variation of the self-type syntax that lets you declare that any class that attempts to mix in the trait must implement the method you specify.

How to use Scala traits as simple mixins

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 8.4, “How to use Scala traits as simple mixins (or, How to mix in Scala traits).”

Problem

You want to design a solution where multiple traits can be mixed into a class to provide a robust design.

Solution

To implement a simple mixin, define the methods you want in your trait, then add the trait to your class using extends or with. For instance, the following code defines a Tail trait: