2 ways to limit classes that can extend traits in Scala

In my earlier post related to Traits in Scala, I have mentioned one point regarding limiting the access of trait to any class in Scala. Yes, it is possible in Scala to limit a trait such a way that it can be extended by very specific sub classes. Basically there are two ways by which you can limit classes that can extend traits,

Solution 1:

By using above syntax you can restrict the usage of a trait via inheritance limited to the child classes of the base classes you mentioned in above syntax.

Let’s take an example for our simplicity,

Code Example:

We have an trait named Bouncable which is responsible for adding behaviour of bouncing to any of our classes in Scala. Now I just want to restrict this behaviour up to child classes of class Tyre. It can be explained using below code example.

Solution 2:


As stated above, you can also write first statement in your trait like “this:<Limiting Base Class Name> =>” which will allow only subclasses of that limiting base class to use this trait.

Code Example:

Now let’s try this with classes ElectronicItemStore and FoodStore by restricting our trait FoodDelivery with class FoodStore.

So that’s it…..!!!!! Quite simple to understand.

Hopefully, this would be informative post for you.

Leave a Reply

Your email address will not be published. Required fields are marked *