Scala case class private constructor is not private

Today I had a strange problem with case class constructors. I wanted to make the constructor private, and it seems like this is not a problem. So I tried this in one of my projects and it works. But in another project, I can call a private constructor, and it compiles. I thought this was something with my idea, so I made a separate class and compiled it using scalac. And it compiles. Here is the code:

package com.test object Main { def main(args: Array[String]) { val bar = Bar("12345") // bar.doStuff() println(bar) } } case class Bar private(foo: String){ private def doStuff():Unit = println("stuff") } 

The funny thing is that if I uncomment bar.doStuff (), it will not compile. Therefore, I suppose private work in this case, but somehow does not work for the constructor. What am I doing wrong? Scalac - 2.11.8

+5
source share
2 answers

The designation val bar = Bar("12345") is an abbreviation for val bar = Bar.apply("12345") , in other words, it calls the apply (automatically generated) companion object of the case class.

The companion object has access to the private constructor, so it works.

(Why do you want to create a constructor for the case private class? This doesn't seem like a good idea).

+10
source

If you want Bar("abc") not to compile, this is just a workaround.

Quick testing in 2.12.3. Does not work in 2.11.8

 case class Bar private (value: String) object Bar { private def apply(v: String) = new Bar(v) // makes the method private def create(value: String): Bar = ... // your own implementation } val bar = Bar("abc") // compile error val bar = new Bar("abc") // compile error val bar = Bar.create("abc") // ok 
+2
source

All Articles