Yeah, as
@ephemient mentions it similar to having an internal constructor. This pattern is more useful if you have an object, as you can’t have a constructor, or if you have a data class, since the pesky copy function opens up the option to instantiate stuff.
This is a bit simplified, but in our case we had a situation where we had something like this:
sealed class PermissionResult {
object Granted : PermissionResult()
object Denied : PermissionResult()
}
And we get this from a suspend function in the same module:
suspend fun checkPermission() : PermissionResult
We wanted to create a function else where that can only be called if we have
Granted
as a value:
fun doSomethingFun(granted: PermissionResult.Granted)
This doesn’t work as is since anyone can reference
Granted
so by using internal implementations like this:
sealed class PermissionResult {
sealed class Granted : PermissionResult() {
internal object Internal : Granted()
}
sealed class Denied : PermissionResult() {
internal object Internal : Denied()
}
}
Means that you are forced to call the
checkPermission
function before you can call
doSomethingFun
which means it’s air tight and there is no way to forget to check the permission 🙂