在Scala中拥有伴随对象的背后原理是什么? [英] What is the rationale behind having companion objects in Scala?

查看:84
本文介绍了在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.

伴侣对象非常适合封装工厂方法之类的东西.不必到处都包含FooFooFactory,您可以让一个带有伴随对象的类承担工厂责任.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆