0
votes

I am not sure if I should choose a class with a companion object in scala instead of using just an object. I just want to use the object anyway, but just because I only need one instance of the class. On the other hand, I am reading that classes with companion objects are a good practice. So, any help about when to use one or another?

Thanks

2
Does the class have state? Does your single instance get constructed with arguments?Bergi
The class doesn't have any state, and it is not constructed with arguments. It is a class used to validate an external object.Samuel Martin
Then you probably need only a (companion) object.Bergi

2 Answers

1
votes
  1. If you want to define a singleton object, you should use the object keyword (it has been introduced into the language specifically for this purpose).
  2. You want to define a singleton object.

By modus ponens it follows:

  • You should use the object keyword,

so no class needed.


However, if you are using some dependency injection framework, and you want that your singleton object is instantiated by the DI container, and if this framework requires that the singleton object is an instance of a plain old Java class with an ordinary constructor, you might want to use class instead.

Under all other circumstances, I don't see any reasons not to use the built in object feature of the language.

0
votes

One popular pattern of companion objects is the following

class Abc {
  ...
}

object Abc {
  def apply(): Abc = new Abc()
}

So instead of writing

val abc: Abc = new Abc()

we can simply write

val abc: Abc = Abc()

But if all you need is a single object, I think there is no harm having just one object.

Not to forget the companion object is the best place to house your implicits.