Reputation: 3350
I am new to scala and trying to understand scala oops concepts. I have create a class as :
class MyComp private{
// some fields and method goes here
}
when I compile it as
scalac MyComp.scala
It create a private constructor . but when I make a companion object than constructor becomes public , I am not able to understand this concept. Please clearify
here is the code for companion object for MyComp class
object MyComp
{
private val comp= new MyComp;
def getInstance= comp;
}
Upvotes: 1
Views: 138
Reputation: 14842
The JVM does not understand the concept of companion objects (and other conpects of the scala language).
Therefore, scalac has no choice but make the constructor of MyComp
public in terms of Java bytecode, since otherwise the JVM would not allow MyComp$
(the class of the companion of MyComp
, often referred to as module class) to instantiate MyComp
. This is, since MyComp
and MyComp$
are completely unrelated from the JVMs point of view.
Scalac tries to keep visibility modifiers on a best effort basis but sometimes must increase the visibility in the bytecode to support some rules that are specific to Scala.
Upvotes: 6