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?
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.
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.
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 .
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.
Yes you can:
class A private (x: Int) {
def this() = this(42)
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With