Is there a way to only allow a single class `A` to...
# announcements
k
Is there a way to only allow a single class
A
to instantiate a class
B
, while keeping
B
itself public? Basically I want
B
to have a private constructor that can also be accessed by
A
but not by a random class
C
. Putting
A
and
B
is the same file doesn't allow
A
to use the private constructor, and even making
B
a nested class of
A
also doesn't work. Is there a solution?
d
why making B nested doesn't work? It allows B to be instantiated by A only?
k
How? This is the code:
Copy code
class A {
    fun foo() = B()
    
    class B private constructor()
}

class C {
    fun bar() = A.B()
}
I want
foo
to compile and
bar
to not compile.
d
ah put the word 'nested' in front of B
and remove private modifier from the constructor
k
There's no
nested
keyword in Kotlin. In Java there is "nothing" for inner,
static
for nested, in Kotlin it's
inner
for inner and "nothing" for nested.
d
sorry, I meant inner
Copy code
class A {
    val b = B()
    inner class B {
        fun test(){

        }
    }
}
class C {
    val a = A()
    val b = A.B()

    fun test() {
        a.b.test()
    }
}
class C doesn't compile here
k
That works, but I don't really want an inner class. It's a good workaround though, I didn't think of that, thanks!
d
Pretty sure you can do A().B() here no?
👍 1
Still a good workaround indeed
k
Ah you're right you can. That's too bad 😞, then I'm still looking for a real solution.
d
I agree this is a bit annoying, compared to java where this isn't a problem
k
It'd be okay if there was any solution at all, but I can't find anything. I've come across this a couple of times already.
p
Same thing here, I wish it had package private at the least.
👍 1
d
spreading A + B and C between modules and using
internal
? 🙂
😒 1
p
There is this long thread on reasons why support/not support package private: https://discuss.kotlinlang.org/t/kotlin-to-support-package-protected-visibility/1544/67 I really prefer something like
friend classes
in c++ over package private.