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()}';
}
}

我该如何在Kotlin中实现这一点,我知道我可以使用静态方法,但是静态方法没有初始化类的目的,有没有一种方法可以在Kotln中实现?

您正在寻找密封类。

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")
}

我同意sealed class是首选方式,但还有另一种选择,即使构造函数私有,并通过companion object中的工厂方法访问它。这样你就可以实现";命名构造函数";。

data class HttpResponse private constructor(
private val code: Int,
private val error: String? = null,
) {
companion object {
fun ok() = HttpResponse(200)
fun notFound() = HttpResponse(404, "Not found")
}
}
fun main() {
val responseOk = HttpResponse.ok()
val responseNotFound = HttpResponse.notFound()
}

密封类是最好的选择:

import java.util.Locale.US
sealed class HttpResponse(val code: Int, val error: String?) {
object Ok : HttpResponse(200, null)
object NotFound : HttpResponse(404, "Not found")
override fun toString() = when (this) {
Ok -> "OK"
NotFound -> "ERROR $code ${error?.uppercase(US)}"
}
}
fun main() {
println(HttpResponse.Ok) // OK
println(HttpResponse.NotFound) // ERROR 404 NOT FOUND
}

由于我无法建议编辑或发表评论,我将在此处添加zOqvxf答案的修改版本

如果以这种方式保持超类参数不公开,就不必担心像注释中提到的HttpResponse.Ok(404)那样的用法。

最新更新