Make a class instantiable only in own file

How do I create a class which I can instantiate in the same file, but not outside of it?

I’m explicitly ruling out internal which I think is not quite restrictive enough for large projects.

The following doesn’t work:

open class C1 private constructor()
// class C2: C1() // init is private

private open class C3
// class C4: C3 // subclass visibility should be as/less permissive as that of superclass

In particular, my problem is that I have something that looks like this:

interface I1 { fun f(): I1 }
interface I2 { fun f(): I2 }

class C: I1, I2 {
    override fun f(): ??? = ...
}

The problem is what to put in place of ???. It there were intersection types in the language, that would be it.

Failing that, I’m trying to create a private interface/class that combines I1 and I2:

private interface I1and2: I1, I2

I do not want to make this union interface public, because otherwise the user might use I1and2 as parameter, and will not be able to accept other types that do implement I1 and I2 but not I1and2.

PS: I’m very strongly convinced that intersection types should be in the language. I was thinking of writing a bit to provide motivation. They are useful in practice. Even more so in the presence of type aliases.

I don’t think there’s a clean solution to this in Kotlin. One thing that can be done is:

private object Foo

class C(p: Foo) : I1, I2 { ... }

Nobody can call C() from the outside, because Foo is private to this file

1 Like