私人 [this] 与私人 [英] private[this] vs private

查看:51
本文介绍了私人 [this] 与私人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 中,我看到诸如对象私有变量之类的功能.从我不太丰富的 Java 背景中,我学会了在必要时关闭所有内容(将其设为私有)并打开(提供访问器).Scala 引入了更严格的访问修饰符.我应该总是默认使用它吗?或者我应该只在某些特定情况下使用它,即使对于同一类的对象,我也需要明确限制更改字段值?换句话说我应该如何选择

In Scala I see such feature as object-private variable. From my not very rich Java background I learnt to close everything (make it private) and open (provide accessors) if necessary. Scala introduces even more strict access modifier. Should I always use it by default? Or should I use it only in some specific cases where I need to explicitly restrict changing field value even for objects of the same class? In other words how should I choose between

class Dummy {
    private var name = "default name"
}

class Dummy {
    private[this] var name = "default name"
}

第二个更严格,我喜欢它,但我应该一直使用它还是只有在我有充分的理由时才使用它?

The second is more strict and I like it but should I always use it or only if I have a strong reason?

正如我所见这里 private[this] 只是一些子案例,而不是 this 我可以使用其他修饰符:包、类或单例对象".所以我会把它留给一些特殊情况.

EDITED: As I see here private[this] is just some subcase and instead of this I can use other modifiers: "package, class or singleton object". So I'll leave it for some special case.

推荐答案

我认为这并不重要,因为任何更改都只会影响一个类.因此,更喜欢 private 而不是 protected 而不是 public 的最重要原因并不适用.

I don't think it matters too much, since any changes will only touch one class either way. So the most important reason to prefer private over protected over public doesn't apply.

在性能真正重要的地方使用 private[this](因为这样您将获得直接字段访问而不是方法).否则,只需选择一种风格,这样人们就不需要弄清楚为什么这个属性是private那个一个是private[这个].

Use private[this] where performance really matters (since you'll get direct field access instead of methods this way). Otherwise, just settle on one style so people don't need to figure out why this property is private and that one is private[this].

这篇关于私人 [this] 与私人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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