What is the use of Object Private in Scala ?



0

I have executed below program but could not be able to understand the perpose of creating object private member variable. Please help me to understand:

package com.scala.training

class PrivateDuck {
  private[this] var private_Age = 0
  def age = private_Age
  def age_ (newAge :Int) = {if (newAge > private_Age) private_Age = newAge else private_Age = 10 }
  def isLess(otherVal: PrivateDuck) = private_Age < otherVal.private_Age   >>> Getting Error Here.
}

class PrivateAnk {
  private var private_Age = 0
  def age = private_Age
  def age_ (newAge :Int) = {if (newAge > private_Age) private_Age = newAge else private_Age = 10 }
  def isLess(otherVal: PrivateAnk) = private_Age < otherVal.private_Age  >>> Not Getting error Here.
}

object example2 extends App {
 
  var f = new PrivateDuck
  f.age_(20)
  println(f.age) 
  var g = new PrivateDuck
  g.age_(30) -----> We can access object private member variable by different instance of same class.
  println(g.age)
  var h = new PrivateAnk
  h.age_(40)
  println(h.age)
 
 
 
}

 

 

 

 

I can access


2 Answer(s)


0

Hi Ankit,

The object-private is the most restrictive access to a method. When you do this, the method is available only to the current instance of the current object. Other instances of the same class cannot access the method.

You mark a method as object-private by placing the access modifier private[this] before the method declaration:

private[this] def isFoo = true

In the following example, the method doFoo takes an instance of a Foo object, but because the isFoo method is declared as an object-private method, the code won’t compile:

class Foo {
    private[this] def isFoo = true
    def doFoo(other: Foo) {
        if (other.isFoo) {  // this line won't compile
            // ...
        }
    }
}

The code won’t compile because the current Foo instance can’t access the isFoo method of the other instance, because isFoo is declared as private[this]. As you can see, the object-private scope is extremely restrictive.

 

Hope this helps.

Thanks.


0

Thanks Abhijit !! 

 

Your Answer

Click on this code-snippet-icon icon to add code snippet.

Upload Files (Maximum image file size - 1.5 MB, other file size - 10 MB, total size - not more than 50 MB)

Email
Password