Scala is not creating private constructor for companion class

137 views Asked by At

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;
}
1

There are 1 answers

4
gzm0 On BEST ANSWER

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.