Created
August 16, 2018 13:28
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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