Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - what is the right way to organize singleton objects hierarchy?

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).

like image 338
noncom Avatar asked Jan 18 '23 14:01

noncom


2 Answers

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

like image 133
oxbow_lakes Avatar answered Jan 22 '23 12:01

oxbow_lakes


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.

like image 22
Nicolas Avatar answered Jan 22 '23 10:01

Nicolas