Here is something that I have came across in Scala that did not cause any problems in Java. Now I just do not know what is the right way of doing this in Scala.
Problem description: I have a Scala Object which denotes an 'abstract' object. It is intended to have a singletonic profile but it is not intended for real use, it is just a bunch of definitions common to it's children-singletons. So instead, I want to use it's children. So there comes the question: since I cannot inherit objects, should the common singleton functionality be realized as a class? As an abstract class? Trait does not suit me because it can't have constructors. If an abstract parent class would do, then how should I access it's singleton (or static) methods if I need them anythere? I realize that there might be a flaw in my design, but since I have this question and can't think of any definitive answer, it is interesting to hear what you say (including design alternatives).
You really should be using a trait
; there is no need for constructors (and, indeed, they make no sense because a scala object
has no constructor):
Here's the shared trait; needA
is the value you need to pass to your constructor. That is, it is required by the functionality of the trait.
trait Common {
def needA: A
def sharedMethod { /* implement me*/ }
}
Then your modules look like this:
object Mod1 extends Common {
val needA = { /* implement me*/ }
}
object Mod2 extends Common {
val needA = { /* implement me*/ }
}
Notice that they specify the required values for the common functionality by using a val
to override a def
Your concern is quite similar to the one that occurs in the design of the companion objects in the collection library in scala.
They choose to use a caommon trait that gather similar functionnalities for their companion objects. To go further, take a look for example at the GenericCompanion
trait and its known subclasses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With