private[this] vs private

后端 未结 9 1075
悲哀的现实
悲哀的现实 2020-11-28 01:35

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

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 02:00

    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.

提交回复
热议问题