Accessing class parameters from companion object in Scala

Asked a question on the topic here:

In the question edit, you asked ‘Why can we access n and d in the toString method?’ I would turn that around and ask you: why shouldn’t we be able to access them? If we understand your thought process on that, we can clear up some confusion.

Because I can access n,d in toString, which shows they are member variables. And companion object can access all members of companion class, even private. But accessing n,d in companion object is not allowed in this case, which means n,d are not members of class. This is the cause of confusion.

I think the thing you’re missing is that n and d are not members - they’re parameters.

In Scala, the entire class body is essentially a function. So since they are function parameters, they are visible everywhere inside that function. But they’re not visible anywhere outside of it, including in the companion object.

When you add val or var, then they become members. But by default, they’re just function parameters, and work as they do in any other function.

2 Likes

Exactly as @jducoeur said, except I would call it constructor instead of function and thus n and d are constructor parameters available throughout the body of the constructor, which is also the body of the class. This design is a bit confusing, to be honest!

I think it actually is better explained as a function which closes over the entire class body.