I have the following code in Dart programming language
class HttpResponse {
final int code;
final String? error;
HttpResponse.ok() : code = 200; <== This functionality
HttpResponse.notFound() <== This functionality
: code = 404,
error = 'Not found';
String toString() {
if (code == 200) return 'OK';
return 'ERROR $code ${error.toUpperCase()}';
}
}
How can I achieve this in Kotlin, I know that I can use static methods, however static methods don't have the purpose of initializing a class, is there a way where this can be achieved in Kotlin?
You're looking for Sealed Classes.
sealed class HttpResponse(val code: Int, val error: String? = null) {
class Ok(code: Int) : HttpResponse(code)
class NotFound(code: Int, error: String?) : HttpResponse(code, error)
override fun toString(): String {
return if (code == 200) "OK"
else "ERROR $code ${error?.toUpperCase()}"
}
}
fun main() {
val okResponse = HttpResponse.Ok(200)
val notFoundResponse = HttpResponse.NotFound(404, "Not found")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With