Private constructor in Kotlin

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

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())


See kotlin documentation here:

https://kotlinlang.org/docs/reference/classes.html#constructors

https://kotlinlang.org/docs/reference/visibility-modifiers.html#constructors

class DontCreateMe private constructor () { /*...*/ }