Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

scala - private[this] vs private

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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a case where private[this] is required to make code compile. This has to do with an interaction of variance notation and mutable variables. Consider the following (useless) class:

class Holder[+T] (initialValue: Option[T]) {
    // without [this] it will not compile
    private[this] var value = initialValue

    def getValue = value
    def makeEmpty { value = None }
}

So this class is designed to hold an optional value, return it as an option and enable the user to call makeEmpty to clear the value (hence the var). As stated, this is useless except to demonstrate the point.

If you try compiling this code with private instead of private[this] it will fail with the following error message:

error: covariant type T occurs in contravariant position in type Option[T] of value value_= class Holder[+T] (initialValue: Option[T]) {

This error occurs because value is a mutable variable on the covariant type T (+T) which is normally a problem unless marked as private to the instance with private[this]. The compiler has special handling in its variance checking to handle this special case.

So it's esoteric but there is a case where private[this] is required over private.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...