Private constructor in Kotlin

Marvin picture Marvin · Oct 20, 2017 · Viewed 25.7k times · Source

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.

Answer

rafal picture rafal · Oct 20, 2017

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