Private constructor in Kotlin

JavaConstructorKotlinVisibility

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

This is possible using a companion object:

class Foo private constructor(val someData: Data) {
	companion object {
		fun constructorA(): Foo {
			// do stuff
			
			return Foo(someData)
		}
	}
	
	// ...
}

Methods inside the companion object can be reached just like if they were members of the surrounding class (e.g. Foo.constructorA())

Solution 3 - Java

Solution 4 - Java

This is the Answer

class Hide private constructor(val someData: Data) {

}

By declaring the constructor private, we can hiding constructor.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarvinView Question on Stackoverflow
Solution 1 - JavarafalView Answer on Stackoverflow
Solution 2 - JavaMarvinView Answer on Stackoverflow
Solution 3 - JavaPrasanthView Answer on Stackoverflow
Solution 4 - JavaAbhinandan ChadaView Answer on Stackoverflow