https://kotlinlang.org logo
Title
p

Paul Dhaliwal

10/13/2019, 9:06 PM
Is it possible to restrict creation of inner class objects to the outer class, so that other classes can’t do new innerObject = OuterClass.InnerClass()
n

nwh

10/13/2019, 9:17 PM
Perhaps
sealed
is what you're looking for
a

Alowaniak

10/13/2019, 9:28 PM
You can make the inner class private (But then you can't expose the type, so if you want to do that then you need to use an interface I guess)
t

tseisel

10/13/2019, 11:10 PM
If you don't need the inner class to be visible to other classes, make it private. Otherwise, make the inner class's constructor private so that only its containing class can instantiate it :
class Outer {
    inner class Inner private constructor() {
        [...]
    }
}
p

Paul Dhaliwal

10/13/2019, 11:12 PM
If I make the constructor private how can I create it in the outer class?
a

Alowaniak

10/14/2019, 8:13 AM
Yea afaict you can't so I think only option is exposing an interface and make the inner implement it But maybe there's another way