private[this] vs private

后端 未结 9 1028
悲哀的现实
悲哀的现实 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.

    0 讨论(0)
  • 2020-11-28 02:22

    private[this] (equivalent to protected[this]) means that that "y" is only visible to methods in the same instance. For example, you could not reference y on a second instance in an equals method, i.e., "this.y == that.y" would generate a compilation error on "that.y". (source)

    so you can do private[this] every time you want but you can have some problem if you need refer it

    0 讨论(0)
  • 2020-11-28 02:22

    When adding the scope to the private modifier (private[X]), it effectively behaves as a “up to” X, where X designates some enclosing package, class or singleton object.

    For example, private[bar], where bar is a package means that every instance of every class belonging to package bar can access whichever member the modifier is restricting.

    In the case of private[this], it means that the member is only accessible for each instance. This becomes more clear in the following example:

    class Foo(foo:Foo){  
       private[this] val i = 2
       println(this.i + foo.i)
    }
    
    >>error: value i is not a member of Foo
    
    class Foo(foo:Foo){  
        private val i = 2
        println(this.i + foo.i)
    }
    
    >>defined class Foo
    

    As you can see, the second Foo doesn’t have any problem since any instance can access the private val i. However for the first Foo there’s an error since each instance cannot see other instance’s i.

    It’s a good practice to write private[this] since it imposes a bigger restriction.

    0 讨论(0)
提交回复
热议问题