Java – How to restrict the instantiation of inner classes outside of Kotlin?

How to restrict the instantiation of inner classes outside of Kotlin?… here is a solution to the problem.

How to restrict the instantiation of inner classes outside of Kotlin?

Having inner and outer classes, I want to limit the instantiation of inner classes only by the scope of the outer class. How can I achieve this in Kotlin? Java provides it in a very simple way. But it seems that in Kotlin I can’t even access private fields from the inner class.

What’s in Kotlin:

class Outer {
    val insideCreatedInner: Inner = Inner()
    inner class Inner
}

val insideCreatedInner = Outer().insideCreatedInner // Should be visible and accessible
val outsideCreatedInner = Outer(). Inner() // I want to disallow this

How Java solves this problem:

class Outer {
    Inner insideCreatedInner = new Inner();
    class Inner {
        private Inner() {}
    }
}

Outer.Inner insideCreatedInner = new Outer().insideCreatedInner;
Outer.Inner outsideCreatedInner = new Outer().new Inner();  'Inner()' has private access in 'Outer.Inner'

Solution

EDITED: To make the val field visible and at the same time hide the inner constructor, it may be useful to use an interface that is visible and makes the implementation private:

class Outer {
    val insideInner: Inner = InnerImpl()

interface Inner {
        // ...
    }
    private inner class InnerImpl : Inner {
        // ...
    }
}

val outer = Outer()
val outsideInner = outer. InnerImpl() // Error! Cannot access '<init>': it is private in 'Inner'

Related Problems and Solutions