I don't want the constructor of a data class to be...
# announcements
a
I don't want the constructor of a data class to be accessible outside a file. Is this a good way to do it? (also what you think of code...)
k
Maybe I'm missing something; why can't you do just do
data class Duration private constructor(val millis: Long)
?
a
image.png
s
it warns, saying that the constructor is exposed via .
copy()
a
also ^
s
you could make it an
internal constructor
?
a
@Shawn but that breaks my encapsulation... I don't want the whole Gradle module to be able to see it, just that file
s
right, right, I was about to say that doesn’t really match your use case entirely
so, just to recap, you want a data class that’s publicly visible but only instantiable from within that particular file?
a
correct
I only want people instantiating it with the getter properties I have defined
ooooof
welp I guess no good solutions then? 😕
s
If only we had package private scoping in Kotlin ...
a
this file is pretty much a combination of all the things I dislike about Kotlin 😛
b
@Andrew Gazelka There’s a few ways to do this 1) make the constructor
private
- Pros: Restricts instance creation within the object itself - Cons: Restricts instance creation with the object itself (this will force you to have those extension values to delegate the creation of a Duration within a companion object or some other nested object)
Copy code
data class Duration private constructor(val milis: Long) {
    companion object {
        fun fromIntMillis(source: Int) = Duration(source.toLong())
    }
}

val Int.millis get() = Duration.fromIntMillis(this)
2) only provide a public interface of your Duration (as you originally proposed) and have a private implementation
2️⃣ 1
Package private still wouldn’t solve his question. That, plus you can easily inject a class into a package to gain visibility, whereas the way Kotlin enforced it ensures it’s truly private only to the given scope
You see the interface approach very often with the Kotlin standard library, coroutines, ktor, etc.
a
imo it is kinda jank though
I feel like Kotlin could implement it better
but I'm guessing the primary reason why access can't be restricted to a file is the JVM
b
The language is designed well beyond the JVM and other platforms don't have a concept of package private. But it does have the concept of private static methods/instance methods/nested classes/etc, which makes file private a candidate on the JVM, in JS, and on LLVM (native)