简体   繁体   English

Scala中的伴随对象和单例类之间有什么区别(Guice)

[英]What's the difference between a companion object and a singleton class in Scala (Guice)

I was wondering what was the difference between a companion object and a class declared with @Singleton ? 我想知道伴侣对象和用@Singleton声明的类有什么区别?

As I understand, you can only have one instance of both. 据我所知,你只能有两个实例。 You can use dependency injection with the class and not with the object but apart from that I don't see much difference to be honest. 您可以在类中使用依赖注入,而不是使用对象,但除此之外我没有看到太多区别。

Well to put it simply. 好吧,简单地说。 A singleton object named the same as a class is called a companion object. 名为与类相同的单个对象称为伴随对象。 Also a companion object must be defined inside the same source file as the class. 还必须在与该类相同的源文件中定义伴随对象。 Also are you using Guice ? 你也在使用Guice吗? That @Singleton is a Guice thing i guess. @Singleton是我猜的Guice。

Very similar stuff. 很相似的东西。 Objects is how Scala allows you to create singleton objects. 对象是Scala允许您创建单例对象的方式。

Things to keep in mind: 要记住的事情:

  • Singleton classes (Java Style) are easier to test than Objects. 单例类(Java样式)比对象更容易测试。 This is because you can create different classes in your tests but you can never create more than one Objects 这是因为您可以在测试中创建不同的类,但是您永远不能创建多个对象
  • Objects cannot have a constructor 对象不能有构造函数
  • Objects cannot be inherited 对象不能被继承

另一个区别是序列化对Scala单例对象的引用使用自定义代码,该代码将始终解析相应类加载器中存在的该对象的单个实例。

As the name reflects, Singleton in Scala has one instance throughout the application life-cycle. 顾名思义,Scala中的Singleton在整个应用程序生命周期中都有一个实例。 Example of a singleton is Nil which denotes an empty List. 单例的示例是Nil,表示空List。

Companion objects on the other hand are helper objects for case classes created in Scala where you can put custom object constructors(apply), implicit conversions, decomposers (unapply). 另一方面,伴随对象是在Scala中创建的case类的辅助对象,您可以在其中放置自定义对象构造函数(apply),隐式转换,分解器(unapply)。 When you define a case class automatically a companion object gets defined. 自动定义案例类时,会定义伴随对象。

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

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