private[this] vs private

后端 未结 9 1052
悲哀的现实
悲哀的现实 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 01:59

    This was tested using scala 2.11.5. Consider the code below

    class C(private val x: Int) {
      override def equals(obj: Any) = obj match {
        case other: C => x == other.x
        case _ => false
      }
    }
    
    println(new C(5) == new C(5)) //true
    println(new C(5) == new C(4)) //false
    

    it will compile and work as this java (1.8) code

    class C {
        private int x;
    
        public C(int x) {
            this.x = x;
        }
    
        public boolean equals(Object obj) {
            if (obj instanceof C) {
                return ((C) obj).x == x;
            }
            else {
                return false;
            }
        }
    }
    
    System.out.println(new C(5).equals(new C(5))); //true
    System.out.println(new C(5).equals(new C(4))); //false
    

    however if you use '[this]' modifier the code below won't compile

    class C(private[this] val x: Int) {
      override def equals(obj: Any) = obj match {
        case other: C => this.x == other.x //problem is here
        case _ => false
      }
    }
    

    This is because in the first case 'x' is accessible on class level, whereas in the second case is it more strict instance level. It means that 'x' can be accessed only from the instance to which it belongs. So 'this.x' is fine but 'other.x' is not.

    You can refer to section 13.5 of "Programming in Scala: A Comprehensive Step-By-Step Guide" book for more details about access modifiers.

提交回复
热议问题