Is there a way to mark a class constructor as priv...
# language-evolution
h
Is there a way to mark a class constructor as private-in-file? Currently I have to use
internal
to get the closest behavior but I really would want it to only be accessible in-file. If not, would be very nice to have.
3
g
I wish.....
a
best alternative I can think of: create a
sealed
public type, with a single
private
implementation.
Copy code
sealed class FooService {
    abstract val name: String
}

private class FooServiceImpl(
    override val name: String
) : FooService()

val defaultFooService: FooService = FooServiceImpl("default")
z
Sealed impls can be in different files in the same source set
I also wish Kotlin had file private 😔
k
You could have an opt-in annotation that itself is not visible outside the file so no-one else can use it:
Copy code
@file:OptIn(PrivateToMe::class)

@RequiresOptIn
private annotation class PrivateToMe

@PrivateToMe
fun foo() { }

fun bar() {
    foo()   
}
That said, this does feel a bit wonky and I haven't actually used it anywhere. I've also found myself often wanting file private access.
z
if i'm that worried about other code in the module accessing something, i'd probably just make a new module
g
For me it is more often just about scope/auto completion pollution, and reminding myself about my own design intentions later on
c
You could have an opt-in annotation that itself is not visible outside the file so no-one else can use it:
IMO, if you're going to do this, use
@Deprecation(level = DeprecationLevel.HIDDEN)
so it's not even in the generated documentation, and you don't need a custom annotation
a
You could have an opt-in annotation that itself is not visible outside the file so no-one else can use it:
Nitpick: anyone could opt-in via compiler args 😅
Copy code
kotlin {
  compilerOptions.optIn.add("PrivateToMe")
}
c
or even just
@Suppress("INVISIBLE_REFERENCE")
if they're going that far 😅
a
technically yes, but that's harder to discover than the documented opt-in flag
👍 1