It's possible to modify the visibility of a constructor. This is sometimes desirable in order to limit how or what can instantiate a class. A common example of this in Java would be the factory pattern in which the instantiation of a class can only be performed by some factory method.
For example, to make a primary constructor private, we can add the private keyword before the constructor keyword when defining the private constructor:
class School private constructor(val name: String)
In this example, School can longer be instantiated because its only constructor is private. To modify the visibility of a secondary constructor, we once again add the visibility modifier before the constructor keyword:
class School private constructor(val name: String) {
private constructor() : this("") {
}
}
It's completely possible to use constructors with different visibilities as well. We could modify the preceding example to make the secondary constructor internal while leaving the primary constructor as private:
class School private constructor(val name: String) {
internal constructor() : this("") {
}
}
The application of visibility modifiers to our constructors gives us the freedom to choose which parts of our application have access to various constructors. This could allow code within the same internal module to access a specific internal constructor while limiting the public constructors that are available. While private is a very common visibility modifier, it's not the only one. In the next section, we'll examine which visibility modifiers are available in Kotlin.