Skip to content

Instantly share code, notes, and snippets.

@prbale
Created December 10, 2017 13:06
Show Gist options
  • Save prbale/5ff7c412f99a810312d896eaef957ec8 to your computer and use it in GitHub Desktop.
Save prbale/5ff7c412f99a810312d896eaef957ec8 to your computer and use it in GitHub Desktop.
Android Kotlin - Sealed Classes
/**
* Declaring Response class as sealed class means,
* It is an Abstract class like in Java. We can have all the features
* in Sealed class which Abstract class has.
* In this example, added one property field to sealed class "Tag" and
* This is overridden in the classes extended to this sealed class.
* Sealed classes are used to have restricted hierarchy.
*/
sealed class Response {
open var tag: String = ""
get() { return "Response" }
}
/**
* Success class: Used to represent success representation of
* "Response" type of class
* This is final class and we can not have any class extending to "Success" class
* In this example, we have overridden the "tag" property set in the Response sealed class.
*/
data class Success(val body: String) : Response() {
override var tag: String = ""
get() { return "Success Response" }
}
/**
* Error class: Used to represent failure representation of
* "Response" type of class
* This is final class and we can not have any class extending to "Error" class
* In this example, we have overridden the "tag" property set in the Response sealed class.
*/
data class Error(val code: String, val errorMessage: String ) : Response() {
override var tag: String = ""
get() { return "Error Response" }
}
/**
* Timeout class: Used to represent timeout representation of
* "Response" type of class
* This is final class and we can not have any class extending to "Timeout" class
* In this example, we have overridden the "tag" property set in the Response sealed class.
*/
object Timeout : Response() {
override var tag: String = ""
get() { return "Timeout" }
}
val response: Response = Success("Success")
when(response) {
is Success -> println("Passed : " + response.tag)
is Error -> println("Failed : " + response.tag)
is Timeout -> println("Oops : " + response.tag)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment