https://kotlinlang.org logo
Title
k

karelpeeters

10/28/2019, 10:14 AM
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

Dias

10/28/2019, 10:27 AM
why making B nested doesn't work? It allows B to be instantiated by A only?
k

karelpeeters

10/28/2019, 10:29 AM
How? This is the 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

Dias

10/28/2019, 10:29 AM
ah put the word 'nested' in front of B
and remove private modifier from the constructor
k

karelpeeters

10/28/2019, 10:30 AM
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

Dias

10/28/2019, 10:31 AM
sorry, I meant inner
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

karelpeeters

10/28/2019, 10:32 AM
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

Dico

10/28/2019, 12:04 PM
Pretty sure you can do A().B() here no?
👍 1
Still a good workaround indeed
k

karelpeeters

10/28/2019, 12:05 PM
Ah you're right you can. That's too bad 😞, then I'm still looking for a real solution.
d

Dico

10/28/2019, 12:07 PM
I agree this is a bit annoying, compared to java where this isn't a problem
k

karelpeeters

10/28/2019, 12:08 PM
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

Pablichjenkov

10/28/2019, 12:21 PM
Same thing here, I wish it had package private at the least.
👍 1
d

Dias

10/28/2019, 12:26 PM
spreading A + B and C between modules and using
internal
? 🙂
😒 1
p

Pablichjenkov

10/28/2019, 12:32 PM
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.