Skip to content

Instantly share code, notes, and snippets.

@alwarren
Created August 16, 2018 13:28
Show Gist options
  • Save alwarren/166af4cf28963c805ffd86b03c35896c to your computer and use it in GitHub Desktop.
Save alwarren/166af4cf28963c805ffd86b03c35896c to your computer and use it in GitHub Desktop.
A generic Kotlin wrapper class for determining the success or failure of some method
sealed class ApiResponse {
class Loading(val loading: Boolean = true) : ApiResponse()
class Success<T>(val data: T) : ApiResponse()
class Error(val message: String) : ApiResponse()
// For demonstration purposes only
companion object {
fun evaluate(response: ApiResponse) {
when(response) {
is ApiResponse.Loading -> {
when(response.loading) {
true -> println("Loading")
false -> println("Not Loading")
}
}
is ApiResponse.Success<*> -> {
when(response.data) {
is String -> println(response.data)
else -> println("Not a string")
}
}
is ApiResponse.Error -> {
println(response.message)
}
}
}
}
}
fun main(args: Array<String>) {
var response: ApiResponse
response = ApiResponse.Loading()
ApiResponse.evaluate(response)
response = ApiResponse.Loading(false)
ApiResponse.evaluate(response)
response = ApiResponse.Success("Success")
ApiResponse.evaluate(response)
response = ApiResponse.Error("Error")
ApiResponse.evaluate(response)
}
/*
Output:
Loading
Not Loading
Success
Error
Process finished with exit code 0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment