Private Designer in Kotlin

In Java, you can hide the main constructor of a class by making it privateand then accessing it using the method public staticinside this 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 one achieve with Kotlin without splitting the class into an interface publicand an implementation private? Creating a constructor privateleads to the fact that it is not accessible from outside the class, not even from the same file.

+6
source share
2 answers

This is possible using a companion object:

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

            return Foo(someData)
        }
    }

    // ...
}

The methods inside the companion object can be achieved in the same way as if they were members of the surrounding class (for example, Foo.constructorA())

+5

- "" .

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
+4

All Articles