This message was deleted.
# getting-started
s
This message was deleted.
a
Kotlin's
private
is class-scoped, so
Bar
can't see
Foo.f()
Make
f
internal
(or public), or move
g
into
Foo
Kotlin can't do this.
private
is strictly per-class, and there's no equivalent of Java's nestmate access between siblings. The closest thing is a
@RequiresOptIn
marker on
f
and the constructor, with
@OptIn
only on `Bar`:
Copy code
@RequiresOptIn(level = RequiresOptIn.Level.ERROR)
annotation class FooInternals

sealed class Superclass {
    class Foo @FooInternals constructor() : Superclass() {
        @FooInternals fun f() {}
    }

    @OptIn(FooInternals::class)
    class Bar : Superclass() {
        fun g(foo: Foo) = foo.f()
        fun newFoo() = Foo()
    }
}
It scales to any number of members and works on constructors, but it's a guardrail, not real privacy: anyone can add
@OptIn
themselves. For hard enforcement,
internal
plus a module boundary is the only other option.
If you want real privacy,
Bar
can’t call it. Kotlin has no sibling access to private members. Put the logic in
Foo
and expose a public method that validates and calls
f()
internally. If only
Bar
should call it, opt-in or
internal
is the closest you’ll get.
Copy code
sealed class Superclass {
    class Foo private constructor() : Superclass() {
        private fun f() {}

        companion object {
            fun create(): Foo = Foo()
            fun <R> withF(foo: Foo, block: () -> R): R { foo.f(); return block() }
        }
    }
}