I am new to Scala and learning to code a personal project in it.
I have this issue and looking around did not help much. So here it is -
abstract class Service{
def containsFeatures(x: Feature*) = ???
}
object Service1 extends Service{..
def containsFeature(x: Feature*)
}
object Service2 extends Service{..
def containsFeature(x: Feature*)
}
Trait Feature
case object A extends Feature
case object B extends Feature
case object C extends Feature
case object D extends Feature
case object E extends Feature
case object F extends Feature
case object G extends Feature
I would like to restrict my code in such a way that Service1 defines which features are possible and which are erroneous. Eg: Service1 allows composing objects A, C, E, G and shows error when other features are supplied.
Is this possible to programmatically restrict this just with our definition of Service1 without modifying the other classes?
I hope my question is clear enough.
Thanks for any suggestions.
If you want scalac to show an error at compile time when a wrong
Feature
is supplied, AND you cannot alter anything other thanService1
then it is not possible. The compiler accepts or rejects a call toService1.containsFeature
based on its interface, but its interface is already defined inService
where it says that it will accept anyFeature
.If you CAN change things about the other code, there are some ways to do this. For instance if you can change everything: