private[this] vs private

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

    In most OOP programming language like java, private fields/methods mean that these private fields/methods are not accessible outside from the class. However, instances/objects of same class can have access to the private fields of objects using assignment operator or by means of copy constructor. In Scala,private[this] is object private,which makes sure that any other object of same class is unable to access private[this] members.

    Example

    1.Without private[this]

    object ObjectPrivateDemo {
    
      def main(args: Array[String]) {
        var real = new User("realUserName", "realPassword")
        var guest = new User("dummyUserName", "dummyPassword")
        real.displayUser(guest)
    
      }
    }
    
    class User(val username:String,val password:String) {
      private var _username=username
      private var _password=password
    
    
    
      def displayUser(guest:User){
    
             println(" guest username="+guest._username+" guest password="+guest._password)
           guest._username= this._username
        guest._password=  this._password
           println(" guest username="+guest._username+" guest password="+guest._password)
    
    
      }
    }
    

    2.Using private[this]

    class User(val username: String, val password: String) {
      private var _username = username
      private[this] var _password = password
    
    
    
      def displayUser(guest: User) {
    
        println(this._username)
        println(this._password)
    
        guest._username = this._username
        // for guest._password it will give this :error  value _password is not member of class User
        guest._password = this._password
    
      }
    }
    

    Hence private[this] makes sure that _password field is only accessible with this.

提交回复
热议问题