DJ180 DJ180 - 20 days ago 4x
Scala Question

Scala: A setter on a singleton object

My Scala application (an Akka service) has a


class has a REST client that retrieves some data, before building the entity.

There should only ever be one instance of this
in my application at any one time.

Obviously, I could use a
object here but the problem is that I want to pass in a mock REST client when running unit tests.

Is invoking a setter on an object considered bad practice in Scala?
If it's done safely and guaranteed to only ever happen once then surely it's a technique that could be employed?

Obviously creating a class with an encapsulated REST client could be done as well, but the problem then is I've to pass this
class all around my code in the absence of a dependency injection framework.

Are there any conventions around this in Scala at the moment?

class PersonBuilder(rest: Rest)
object PersonBuilder extends PersonBuilder(LiveRest)
object TestPersonBuilder extends PersonBuilder(MockRest)

If you don't want constructor args, use traits.

trait PersonBuilder {
  def rest: Rest
object PersonBuilder extends PersonBuilder {
  override val rest = LiveRest