gpt4 book ai didi

android - Kotlin 命名构造函数

转载 作者:行者123 更新时间:2023-12-02 13:15:27 24 4
gpt4 key购买 nike

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

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()}';
}
}
我如何在 Kotlin 中实现这一点,我知道我可以使用静态方法,但是静态方法没有初始化类的目的,有没有办法在 Kotlin 中实现这一点?

最佳答案

您正在寻找 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")
}

关于android - Kotlin 命名构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64489477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com