gpt4 book ai didi

kotlin - 如何在Kotlin中将不良字符串作为伪 bool 值处理?

转载 作者:行者123 更新时间:2023-12-02 13:00:20 25 4
gpt4 key购买 nike

假设我正在使用gson在Kotlin数据类中对json进行序列化和反序列化。其中一个值是设置为"is"或“否”的字符串,另一个是设置为“开”或“关”的字符串。是的,这是可怕的做法,但让我们假设它不能更改。

在Kotlin中处理此问题的最佳方法是什么?

APIdata.json

{
"value" : "On",
"anotherValue" : "Yes"
}

APIdata.kt
data class APIdata (val value : String, val anotherValue: String)

为了获取和设置,我希望能够将它们都视为 bool(boolean) 值。

最佳答案

您可以使用映射函数和相应的构造函数,也可以定义get方法:

data class APIdata(val value: String, val anotherValue: String) {
fun mapToBoolean(string: String) =
when (string.toLowerCase()) {
"yes" -> true
"on" -> true
else -> false
}

constructor(value: Boolean, anotherValue: Boolean) :
this(if (value) "on" else "off", if (anotherValue) "yes" else "no")

fun getValue(): Boolean {
return mapToBoolean(value)
}


fun getAnotherValue(): Boolean {
return mapToBoolean(anotherValue)
}
}

在这种情况下,使用 data class可能会产生误导,因为Kotlin编译器会假设 hashCodeequalsvalue而不是 anotherValue来生成 StringBoolean。最好这样设计自己:
class APIdata( val value: String, private val anotherValue: String) {
fun mapToBoolean(string: String) =
when (string.toLowerCase()) {
"yes" -> true
"on" -> true
else -> false
}

constructor(value: Boolean, anotherValue: Boolean) :
this(if (value) "on" else "off", if (anotherValue) "yes" else "no")

fun getValue(): Boolean {
return mapToBoolean(value)
}


fun getAnotherValue(): Boolean {
return mapToBoolean(anotherValue)
}

override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false

other as APIdata

if (getValue() != other.getValue()) return false
if (getAnotherValue() != other.getAnotherValue()) return false

return true
}

override fun hashCode(): Int {
var result = getValue().hashCode()
result = 31 * result + getAnotherValue().hashCode()
return result
}
}

关于kotlin - 如何在Kotlin中将不良字符串作为伪 bool 值处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49615510/

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