00.scala2014. 3. 28. 13:12
반응형

I haven't had the need for this syntax yet, but I just saw some code that shows how to create a private primary constructor in Scala, and I thought I'd test it and share an example of it.

In the example below, I've made the primary constructor of the Order class private:

object PrivateConstructorTests {

  def main(args: Array[String]) {
    val o = new Order  // this won't compile
  }

}

// note the 'private' keyword here
class Order private() {
  
  def this(orderId: Long) {
    this();
    // more code here ...
  }  
  
}

Private primary constructor syntax

The primary constructor is made private in this unusual looking line of code:

class Order private() {

This syntax might make a little more sense if I show a primary constructor that takes a parameter:

class Order private(customerId: Long) {

In either case, the "private" keyword in the location shown makes the primary constructor private.

Getting back to the first source code example, as you saw from the comment included in the source code, this line of code won't even compile because the primary constructor is private:

val o = new Order  // this won't compile

Again, I haven't had a need to use this Scala "private constructor" syntax yet, but I used to use it in Java when I wanted to enforce the Singleton Pattern, as is done in the Java Calendar class.

Posted by 1010