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;
}
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 allowMyComp$
(the class of the companion ofMyComp
, often referred to as module class) to instantiateMyComp
. This is, sinceMyComp
andMyComp$
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.