如何在 Scala 中创建只读类成员?
我想创建一个 Scala 类,其中一个 var 从类外部是只读的,但仍然是一个 var。我该怎么做呢?
如果是val,则无需执行任何操作。默认情况下,定义意味着公共访问和只读。
I want to create a Scala class where one of its var is read-only from outside the class, but still a var. How can I do it?
If it was a val, there was no need to do anything. By default, the definition implies public access and read-only.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将公共“getter”定义为私有
var
。Define a public "getter" to a private
var
.使用“getter”方法定义一个特征:
一个扩展此特征的类,并且其中包含您的变量
适当限制此类的可见性。
拥有专用接口还允许您在运行时使用多个实现类,例如更有效地覆盖特殊情况、延迟加载等。
Define a trait with the "getter" method:
Define a class which extends this trait, and which has your variable
Restrict the visibility of this class appropriately.
Having a dedicated interface allows you also to use multiple implementation classes at runtime, e.g. to cover special cases more efficiently, lazy loading etc.