Kotlin 命名构造函数

And*_*rea 6 android kotlin

我在Dart编程语言中有以下代码

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()}';
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能在Kotlin中实现这一点,我知道我可以使用静态方法,但是静态方法没有初始化类的目的,有没有办法在Kotlin中实现这一点?

Ben*_*o99 9

您正在寻找密封课程

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")
}
Run Code Online (Sandbox Code Playgroud)

  • 默认情况下,密封类无法实例化。尝试创建 `HttpResponse(100, "Test")` 会引发错误。 (3认同)