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:
Syntax
trait <Trait Name> extends <Base Class Name>

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.

//We have two classes "Tyre" and "Ball"
class Tyre
abstract class Ball

//Now Bouncable is restricted to subclasses of Tyre
trait Bouncable extends Tyre

//This will work perfectly fine
class TubeTyre extends Tyre with Bouncable
class TublessTyre extends Tyre with Bouncable

//Will not compile
class BasketBall extends Ball with Bouncable
abstract class FootBall extends Ball with Bouncable
Solution 2:
Syntax
trait <Trait Name> {
    this: <Base Class Name> => 
    //....Other Code 
}

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.

//Base abstract class 
abstract class Store

//Base classes 
class ElectronicItemStore extends Store
class FoodStore extends Store

trait FoodDelivery { 
    this:FoodStore =>
}

//This make sense, even by reading it
class FoodBazaar extends FoodStore with FoodDelivery
class PizzaStore extends FoodStore with FoodDelivery

//doesn't make sense(even by reading it), so won't compile
class SamsungMobileStore extends ElectronicItemStore with FoodDelivery

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 *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>