我在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中实现这一点?
您正在寻找密封课程。
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)
| 归档时间: |
|
| 查看次数: |
3073 次 |
| 最近记录: |