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
1 | trait <Trait Name> extends <Base Class Name> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //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
1 2 3 4 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //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.