private[this] vs private

后端 未结 9 1054
悲哀的现实
悲哀的现实 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:09

    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

    It's better to use private[this] if you plan to synchronize the variable.

    Here a good example from the scala style guide of the Spark team:

    // The following is still unsafe.
    class Foo {
      private var count: Int = 0
      def inc(): Unit = synchronized { count += 1 }
    }
    
    // The following is safe.
    class Foo {
      private[this] var count: Int = 0
      def inc(): Unit = synchronized { count += 1 }
    }
    

提交回复
热议问题