Why Kotlin doesn't allow creation of public instances of private inner classes unlike Java?
Works in Java:
public class Test {
public A a = new A();
private class A {
}
}
Doesn't work in Kotlin (A
class has to be public
):
class Test {
var a = A()
// ^
// 'public' property exposes its private type 'A'
private inner class A
}
I would assume because there isn't really a case where it seems like the right thing to do. Any code accessing the property a
would not have access to its type. You couldn't assign it to a variable. Test.A myVar
declaration outside of the Test
class would error out. By not allowing it, the code will be forced to be more consistent. A better question would be why would Java allow it? Other languages, such as swift, have the same restriction.
https://kotlinlang.org/docs/reference/visibility-modifiers.html#classes-and-interfaces
states:
NOTE for Java users: outer class does not see private members of its inner classes in Kotlin.
For your usecase, you can use Nested Classes
In private inner classes
you are only able to access members of your outer class.
I think the kotlin team implemented it that way, so that is possible to reduce the scope of members in private inner classes
to be accessible only inside the inner class
. I think this is not possible in Java.