with

How to define a Scala trait so it can only be subclassed by a certain type

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 8.6, “How to mark a Scala trait so it can only be subclassed by a certain type.”

Problem

You want to mark your trait so it can only be used by types that extend a given base type.

Solution

To make sure a trait named MyTrait can only be mixed into a class that is a subclass of a type named BaseType, begin your trait with a this: BaseType => declaration, as shown here:

Scala trait examples and syntax

This page contains a collection of Scala trait examples. I created many of these examples when I was writing the Scala Cookbook. Unlike the Cookbook, where I explain these examples in great detail, on this page I’m just sharing many of the examples so you can use this as a trait reference page. (The Cookbook actually contains more examples than this page.)

Without any more introduction, here are the examples.