oday
09/02/2022, 9:23 AMsealed interface EmptyResult {
object Success : EmptyResult
class Failure(val error: Throwable) : EmptyResult
}
sealed class DeleteResult : EmptyResult
sealed class SetResult : EmptyResult
Why can’t I access SetResult.Success or DeleteResult.Success?oday
09/02/2022, 9:25 AMinline fun EmptyResult.fold(
onSuccess: () -> Unit,
onFailure: (exception: Throwable) -> Unit,
): Unit = when (this) {
is EmptyResult.Success -> onSuccess()
is EmptyResult.Failure -> onFailure(error)
}
oday
09/02/2022, 9:25 AMYoussef Shoaib [MOD]
09/02/2022, 9:43 AMtypealias DeleteResult = EmptyResult
oday
09/02/2022, 9:50 AMKlitos Kyriacou
09/02/2022, 9:50 AMEmptyResult
interface to also have their own separate Success
and Failure
subclasses. That's not what you have though. The classes Success
and Failure
and also DeleteResult
and SetResult
are all directly implementing EmptyResult
.oday
09/02/2022, 9:50 AModay
09/02/2022, 9:50 AModay
09/02/2022, 9:50 AMStephan Schroeder
09/02/2022, 9:50 AMDeleteResult
and SetResult
seem confused. First you define subtypes of EmptyResult within the body, then outside of it, which isn't wrong but maybe not what you intended. Success
and Failure
aren't properties of EmptyResult
but subtypes.
It's also strange that DeleteResult
and SetResult
are sealed classes, because you can't instanciate those. You'd have to create subtypes to those as well, which is probably not what you've intended.Klitos Kyriacou
09/02/2022, 9:53 AMtypealias DeleteResult = EmptyResult
would work, but there would be no type safety to prevent a DeleteResult being assigned to a SetResult. Maybe what you want is a parameterized interface, something like class DeleteResult : EmptyResult<DeleteResult>
oday
09/02/2022, 9:54 AModay
09/02/2022, 9:54 AMYoussef Shoaib [MOD]
09/02/2022, 10:25 AMsealed interface EmptyResult<R> {
class Success<R> private constructor(): EmptyResult<R>
class Failure<R>(val error: Throwable) : EmptyResult<R>
companion object {
private val successObject = Success<Nothing>()
// Reified to prevent R from being Nothing
inline fun <reified R> Success(): EmptyResult.Success<R> = successObject as Success<R>
}
}
object DeleteResultType
object SetResultType
typealias DeleteResult = EmptyResult<DeleteResultType>
typealias SetResult = EmptyResult<SetResultType>
This should be typesafe and allow you to treat DeleteResult
and SetResult
as if they were there own thing, while ensuring that they're assignment-incompatible.