在Scala中拥有伴随对象的背后原理是什么? [英] What is the rationale behind having companion objects in Scala?
问题描述
是否存在需要用于类的伴侣对象(单例)的情况?为什么我要创建一个类,例如Foo
并为其创建一个伴随对象?
Is there a case where a companion object (singleton) for a class is needed? Why would I want to create a class, say Foo
and also create a companion object for it?
推荐答案
伴随对象基本上提供了一个放置类静态"方法的位置.此外,伴随对象或伴随模块具有对类成员(包括私有成员)的完全访问权限.
The companion object basically provides a place where one can put "static-like" methods. Furthermore, a companion object, or companion module, has full access to the class members, including private ones.
伴侣对象非常适合封装工厂方法之类的东西.不必到处都包含Foo
和FooFactory
,您可以让一个带有伴随对象的类承担工厂责任.
Companion objects are great for encapsulating things like factory methods. Instead of having to have, for example, Foo
and FooFactory
everywhere, you can have a class with a companion object take on the factory responsibilities.
这篇关于在Scala中拥有伴随对象的背后原理是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!