您的位置:首页 > 其它

private[this]

2014-06-09 00:00 162 查看
摘要: private private[this]

In Scala (as well as in Java or C++), a method can access the private fields of all objects of its class.

For example,

class Counter {
private var value = 0
def increment() {
value += 1
}
def isLess(other: Counter) = value < other.value
// Can access private field of other object
}

Accessing other.value is legal because other is also a Counter object.

Scala allows an even more severe access restriction, with the private[this] qualifier:

private[this] var value = 0 // Accessing someObject.value is not allowed

Now, the methods of the Counter class can only access the value field of the current object, not of other objects of type Counter. This access is sometimes called object-private, and it is common in some OO languages, such as SmallTalk.

With a class-private field, Scala generates private getter and setter methods. However, for an object private field,no getters and setters are generated at all.

Note:

Scala allows you to grant access rights to specific classes. The private[ClassName] qualifier states that only methods of the given class can access the given field. Here, the ClassName must be the name of the class being defined or an enclosing class. (See Section 5.8, “Nested Classes,” on page 60 for a discussion of inner classes.) In this case, the implementation will generate auxiliary getter and setter methods that allow the enclosing class to access the field. These methods will be public because the JVM does not have a fine-grained access control system, and they will have implementation-dependent names.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐