rocketraman
09/09/2021, 7:46 PMServiceException
to an implementation of some sealed payload interface T
e.g.:
inline fun <reified T> ServiceException.toError(): T {
return when(this) {
is InvalidInputException -> InvalidInputError(...)
is PermissionDeniedException -> PermissionDeniedError(...)
} as T
}
The payload type T
is some interface. I can cast the result of the when
to T as shown, but then forgetting to implement T
in each of these error types will result in a run-time exception.
What would be the best way to create a re-usable function here that is compile-time type-validated, just as if that function were literally inlined?uli
09/10/2021, 9:35 AMT
inline fun <reified T> ServiceException.toError(): T {
return when(this) {
is InvalidInputException -> InvalidInputError(...) as T
is PermissionDeniedException -> PermissionDeniedError(...) as T
}
}
uli
09/10/2021, 9:35 AMrocketraman
09/10/2021, 5:06 PMrocketraman
09/10/2021, 5:11 PMT
could be defined as a union type and then I believe type checking would work correctly.