Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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'
like image 981
Yevhenii Nadtochii Avatar asked Oct 21 '25 13:10

Yevhenii Nadtochii


1 Answers

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'
like image 107
karmakaze Avatar answered Oct 23 '25 06:10

karmakaze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!