Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private constructor in Kotlin

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.

like image 321
Marvin Avatar asked Oct 20 '17 10:10

Marvin


People also ask

What is private constructor in Kotlin?

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 ...

How do you call a private constructor in Kotlin?

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.

What is a private constructor?

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.

Can we use constructor in private?

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.


1 Answers

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 
like image 196
rafal Avatar answered Oct 11 '22 05:10

rafal