Reputation: 49
I've been learning Kotlin and I'm currently faced with two problems.
What's the usage of private constructors?
What's the usage of private parameters in constructors?
We cannot even create an instance of a class that has a private constructor
Private parameters in constructors...
Thus, they will be visible only in that class? But, they do it and without the private
modifier in constructor.
Any help is appreciated!
Upvotes: 0
Views: 85
Reputation: 5635
Private constructors
It's similar to java
. You can forbid creation of class instances if a class has only private constructors. Or you can allow to this class to be responsible of creation of its instances (like it is done in the Singleton pattern).
class Singleton private constructor(val name: String) {
companion object {
fun getInstance(): Singleton {
return Singleton() // Simplified
}
}
}
Constructor private parameters
If a constructor of a class C
has a val s: String
parameter it becomes an instance public property property and can be accessed like C.s
. If we will declare such parameters as a private
it will become an instance private property.
class Holder(private val pri: String, val pub: String) {
}
val holder = Holder("private", "public")
holder.pub // contains "public"
holder.pri // not accessible
Upvotes: 2
Reputation: 811
This is same as Java private constructor, you can instantiate the class by using companion object methods.
class Foo private constructor(val someData: Data) {
companion object {
fun constructorA(): Foo {
// do stuff
return Foo(someData)
}
}
// ...
}
Upvotes: 1