Scala private modifier scope

I have code with a companion object and a specific 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 the same package also has access to this private constructor. I added a private [this] so that others would not have access to it, but not be an ally. Can I have private properties only for class and companion object?

+3
source share
1 answer

This code does not compile. Both Employeeand Workerare trying to get access to a private constructor and rightfully denied access.

Your question is about a private variable, but there is no variable declared private.

, , . , , .

+1

All Articles