Scala case class private constructor isn't private -
today encountered strange problem case class constructors. wanted make constructor private , seems isn't problem. i've tried in 1 of projects , works. in project can invoke private constructor , compiles. thought ide, made standalone class , compile scalac. , compiles. here 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 if uncomment bar.dostuff() won't compile. assume private works in case, somehow doesn't work constructor. doing wrong? scalac 2.11.8
the notation val bar = bar("12345")
shorthand val bar = bar.apply("12345")
, in other words, calls apply
method of (automatically generated) companion object of case class.
the companion object has access private constructor, that's why works.
(why want make constructor of case class private
? doesn't sound idea).
Comments
Post a Comment