Accesing private members of Class from companion object

In Programming in Scala 4 edition by Martin Odersky I found

A class and its companion object can access each other’s private members.

I wonder how can companion object access private members of class If there is none instance of class object availabile.

It means that inside the object you can access the private members of any instance of the class for example:

final class Foo(val x: Int) {
  private final val y: Int = x * x
}

object Foo {
  def bar(foo: Foo): Int = foo.y
}

You probably meant foo.y

1 Like