Private constructors

#1

I have a

class E private (aList: List[T])

object E {
    def apply(something: T) = new E(List(something))
}

object MyTest {
  def main(args: Array[String]) {
     val myTobj = new T(...)
     println(new E(myTobj))
  }}

I am confused now because although in the code above I forgot to make the E object through the apply method of the companion object, it still compiles and works.

I removed the ‘new’ command in the println statement i.e. println(E(myTobj)) and it does the same thing.

Did I build the object using the apply method and the new command was ignored or did the privateness of E’s constructor not get enforced?

There is a post here about case class constructors but this is not a case class.

#2

I get

error: constructor E in class E cannot be accessed in object MyTest
1 Like
#3

I failed to reproduce that here: https://scastie.scala-lang.org/MQuQR0Z3R2yQ95lCWF89Hg

Can you see if you can reproduce?

#4

I too get that message in the REPL which is confusing. I have done sbt clean a number of times to make sure its not working from old sources but no error is thrown.