简体   繁体   English

Scala:单例对象上的setter

[英]Scala: A setter on a singleton object

My Scala application (an Akka service) has a PersonBuilder class 我的Scala应用程序(Akka服务)有一个PersonBuilder

This PersonBuilder class has a REST client that retrieves some data, before building the entity. PersonBuilder类具有REST客户端,可在构建实体之前检索某些数据。

There should only ever be one instance of this PersonBuilder in my application at any one time. 在我的应用程序中,任何时候都应该只有一个这个PersonBuilder 实例

Obviously, I could use a PersonBuilder object here but the problem is that I want to pass in a mock REST client when running unit tests. 显然,我可以在这里使用PersonBuilder对象,但问题是我想在运行单元测试时传入一个模拟REST客户端。

Is invoking a setter on an object considered bad practice in Scala? 在Scala中调用被认为是不良实践的对象的setter? 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 PersonBuilder class all around my code in the absence of a dependency injection framework. 显然,也可以使用封装的REST客户端创建一个类,但问题是我在没有依赖注入框架的情况下将所有PersonBuilder类传递PersonBuilder我的代码。

Are there any conventions around this in Scala at the moment? 目前Scala还有任何约定吗?

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

If you don't want constructor args, use traits. 如果您不想使用构造函数args,请使用traits。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM