private[this] vs private

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

    To elaborate on the performance issue Alexey Romanov has mentioned, here are some of my guesses. Quotes from book "Programming in Scala: A Comprehensive Step-by-Step Guide, 2nd Edition" Section 18.2:

    In Scala, every var that is non-private member of some object implicitly defines a getter and a setter method with it.

    To test it out, this code will cause compilation error:

    class PrivateTest{
      var data: Int = 0
      def data_=(x : Int){
        require(x > 0)
        data = x
      }
    }
    

    Scala complains about error: ambiguous reference to overloaded definition. Adding override keyword to data_= won't help should prove that the method is generated by the compiler. Adding private keyword to variable data will still cause this compilation error. However, the following code compiles fine:

    class PrivateTest{
      private[this] var data: Int = 0
      def data_=(x : Int){
        require(x > 0)
        data = x
      }
    }
    

    So, I guess private[this] will prevent scala from generating getter and setter methods. Thus, accessing such variable will save the overhead of calling the getter and setter method.

提交回复
热议问题