Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected difference in behavior seemingly due to using private[this] instead of private

Tags:

scala

These two classes behave differently; the cause seems related to the use of a private[this] declaration instead of a private. Can somebody explain why, please?

  • private:

    class Person(
      private var _age: Int
    ) {
      if (_age < 0) { _age = 0 }
    
      def age = _age
      def age_=(newAge: Int) {
        if (newAge > _age) { _age = newAge }
      }
    }
    

    In the REPL, this behaves as I was expecting for both classes; that is, the age method gets _age, which has been set to the appropriate value during construction:

    scala> val person = new Person(-1)
    person: Person = Person@200a570f
    
    scala> person.age
    res0: Int = 0
    
  • private[this]:

    class Person(
      private[this] var _age: Int
    ) {
      if (_age < 0) { _age = 0 }
    
      def age = _age
      def age_=(newAge: Int) {
        if (newAge > _age) { _age = newAge }
      }
    }
    

    In the REPL, person.age appears to take the value of _age prior to the evaluation of the if expression. It works as expected after using the setter, though:

    scala> val person = new Person(-1)
    person: Person = Person@6f75e721
    
    scala> person.age
    res0: Int = -1
    
    scala> person.age = 0
    person.age: Int = 0
    
    scala> person.age
    res1: Int = 0
    
like image 478
Pablo Avatar asked Aug 21 '15 09:08

Pablo


1 Answers

This is a known bug, namely SI-6880.

like image 75
kiritsuku Avatar answered Sep 22 '22 15:09

kiritsuku