Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala private access modifier scope

Tags:

scala

I have code with companion object and defined constructor as private:

class Person private[Person] (var age: Int, var name: String) {
  private[Person] def this(name: String) = this(0, name)
}

private class Employee(age: Int, name: String) extends Person(age, name)

private class Worker(age: Int, name: String) extends Person(age, name)

object Person {
  def prettyPrint(p: Person) = println("name:%s age:%s".format(p.name, p.age))
  def apply(age: Int, name: String) = new Person(age, name)
  def apply() = new Person(0, "undefined")
  def apply(age: Int, name: String, personType: String): Person = {
    if (personType == "worker") new Worker(age, name)
    else if (personType == "employee") new Employee(age, name)
    else new Person(age, name)
   }

}

My question is why another object in same package also have access to this private constructor. I added private[this] so others didn't have access to it but nor companion had. Can I have private properties for class and companion object only ?

like image 900
Lukasz Avatar asked Aug 10 '26 01:08

Lukasz


1 Answers

This code does not compile. Both Employee and Worker try to access the private constructor, and are rightfully denied access.

Your question speaks of a private variable, but there's no variable declared private.

So either your example is incomplete, or it is incorrect. Please correct the example so we can answer the question.

like image 90
Daniel C. Sobral Avatar answered Aug 13 '26 00:08

Daniel C. Sobral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!