Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make the primary constructor private while keeping auxiliary constructors public in Scala?

As I intend only overloaded constructors for public use to create the class instances I'd like to make the primary constructor private. Is this possible in Scala?

like image 936
Ivan Avatar asked Feb 27 '12 09:02

Ivan


People also ask

What is the purpose of auxiliary constructor in Scala?

The auxiliary constructor in Scala is used for constructor overloading and defined as a method using this name. The auxiliary constructor must call either previously defined auxiliary constructor or primary constructor in the first line of its body.

What is primary constructor in Scala?

The primary constructor of a Scala class is a combination of: The constructor parameters. Methods that are called in the body of the class. Statements and expressions that are executed in the body of the class.

How do we define an auxiliary constructor?

Auxiliary constructors are defined by creating methods named this . Each auxiliary constructor must begin with a call to a previously defined constructor. Each constructor must have a different signature. One constructor calls another constructor with the name this .

How do I call a super constructor in Scala?

When you define a subclass in Scala, you control the superclass constructor that's called by its primary constructor when you define the extends portion of the subclass declaration.


2 Answers

Yes you can:

class A private (x: Int) {
  def this() = this(42)
}
like image 141
Nicolas Avatar answered Oct 05 '22 07:10

Nicolas


Yes - you can determine the visibility of the primary constructor by specifying the modifiers after the class name, e.g.:

class Foo private (a: Int, b: String) {
   // ...
}

And then of course the auxiliary constructors can still (in fact, must) reference this primary constructor, while still being declared as public.

like image 20
Andrzej Doyle Avatar answered Oct 05 '22 07:10

Andrzej Doyle