In Java it's possible to hide a class' main constructor by making it private
and then accessing it via a public
static
method inside that class:
public final class Foo { /* Public static method */ public static final Foo constructorA() { // do stuff return new Foo(someData); } private final Data someData; /* Main constructor */ private Foo(final Data someData) { Objects.requireNonNull(someData); this.someData = someData; } // ... }
How can the same be reached with Kotlin without separating the class into a public
interface and a private
implementation? Making a constructor private
leads to it not being accessible from outside the class, not even from the same file.
The kotlin private constructor is one of the constructor types, and it is used to stop the object creation for the unwanted case; if the user has decided to create the object for themselves accordingly, the memory will be allocated for the specific instance and also the class methods which is used for referring the ...
This is possible using a companion object: class Foo private constructor(val someData: Data) { companion object { fun constructorA(): Foo { // do stuff return Foo(someData) } } // ... } Adding to this for completeness. From Java you can only call methods inside a companion object only with Companion like Foo.
A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.
Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.
You can even do something more similar to "emulating" usage of public constructor while having private constructor.
class Foo private constructor(val someData: Data) { companion object { operator fun invoke(): Foo { // do stuff return Foo(someData) } } } //usage Foo() //even though it looks like constructor, it is a function call
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