I have a function that maps a sealed exception typ...
# codereview
r
I have a function that maps a sealed exception type
ServiceException
to an implementation of some sealed payload interface
T
e.g.:
Copy code
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?
u
Not sure , but I would guess casting each payload directly should let the compiler complain if the type is not a
T
Copy code
inline fun <reified T> ServiceException.toError(): T {
  return when(this) {
    is InvalidInputException -> InvalidInputError(...) as T
    is PermissionDeniedException -> PermissionDeniedError(...) as T
  }
}
Not sure though, why the compiler can not detect that issue in your original code
r
No, that makes no difference. The compiler only seems to check the types at the use site, not the call site. I found this stale KEEP by @juangamnik which I believe is this issue: https://github.com/Kotlin/KEEP/pull/35.
If union types were supported, then
T
could be defined as a union type and then I believe type checking would work correctly.