Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin named constructors

Tags:

android

kotlin

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?

like image 967
Andrey Avatar asked Aug 31 '26 04:08

Andrey


1 Answers

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")
}
like image 71
zOqvxf Avatar answered Sep 02 '26 21:09

zOqvxf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!