Skip to content

Instantly share code, notes, and snippets.

@jonreeve
Last active June 16, 2021 09:05
Show Gist options
  • Save jonreeve/cf4cf4d386e7c313859556efa695f23c to your computer and use it in GitHub Desktop.
Save jonreeve/cf4cf4d386e7c313859556efa695f23c to your computer and use it in GitHub Desktop.
Sealed failure types - flat but restrictive
package com.myapp.api.common.failure
import com.myapp.api.common.failure.differentpackage.ApiCall3Failure
// This Common errors type has to know all the other types to include it in, which isn't nice. They can't include it.
// Also, they all must be in the same module (not sooo bad) and PACKAGE (very restrictive), so this third one won't work
// as it's been put in another package.
sealed class Common() : ApiCall1Failure, ApiCall2Failure /*, ApiCall3Failure */ {
object NetworkFailure : Common()
object ServerFailure : Common()
}
sealed interface ApiCall1Failure {
object Specific1 : ApiCall1Failure
}
sealed interface ApiCall2Failure {
object Specific2 : ApiCall2Failure
}
fun test() {
val fail: ApiCall2Failure = ApiCall2Failure.Specific2
// This is sealed, can generate the branches, all mixed in with one another, flat.
// Whether that's a good or a bad thing is another matter; could be useful to group the common ones to delegate handling.
when (fail) {
Common.NetworkFailure -> TODO()
Common.ServerFailure -> TODO()
ApiCall2Failure.Specific2 -> TODO()
}
}
package com.myapp.api.common.failure.differentpackage
sealed interface ApiCall3Failure {
object Specific3 : ApiCall3Failure
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment