Yevhenii Nadtochii
Yevhenii Nadtochii

Reputation: 704

How to restrict instantiation of inner class only inside outer in Kotlin?

Having inner & outer classes I want to restrict instantiation of inner only by the scope of outer class. How can I achieve this in Kotlin ? Java provides it in a very easy way. But is seems that in Kotlin I can't access private field even from inner class.

What Kotlin has:

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 solve this:

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'

Upvotes: 4

Views: 714

Answers (1)

karmakaze
karmakaze

Reputation: 36154

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's visible and make 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'

Upvotes: 3

Related Questions