Suppose there’s a tree type and a tree node type. You want to allow modifying node pointers only from the tree code, because it preserves some invariants. In Java, you can simply make the Node a (static) inner class of Tree, make the pointer fields private, have a public getter and then either use a private setter or simply manipulate the pointer from the Tree class. Seems like there’s no good way to do that in Kotlin.

In most cases you can get away with making the type itself private. In your case you’ll have to go the extra way by having a Node interface and a NodeImpl class (which is private). Btw. trees are typically implemented immutable (but indeed don’t have to).

This should work although it doesn’t stop “invalid” nodes from being passed in by users, but node ownership is always a problem in mutable trees (copying to a locally created not is always safer in that sense).

If you are separating your code into different modules you can even use an abstract class with an internal constructor instead of the interface. That way no one outside of the module can create “invalid” nodes.

Kotlin allows to do that but uses different default behavior.
Inner class in Kotlin by default behave like Java’s class with static modifier on inner class. So it’s completely separate class without reference to the parent.
If you want to get access to parent class like in java without static you should add modifier inner to Kotlin’s internal class.
It just forces you to be more explicit for such case and it’s harder to leak parent class accidentally like in java, when you just forgot to mark inner class static, it’s actually not the best practice in most cases

Gildor : He (and I) want to do the exact opposite of “inner”. Tree wants to modify the internals of Node, but also wants to hang out Node(s) to other clients that look immutable. Only Tree should be able to modify the guts of Node.

The solution given works, but… it’d be nice if the language supported it, instead of having to write boiler plate for this pattern every time.