【问题标题】:Android Kotlin convert data class into enum classAndroid Kotlin 将数据类转换为枚举类
【发布时间】:2020-05-18 18:30:30
【问题描述】:

这里的CustomerBodyModel 是数据类。我需要UsertoCustomer() 的内部函数,将User class 转换为Customer class。我坚持将Boolean type 更改为Customer.Type

客户类别

data class Customer(
    val id: String,
    val bodyModel: BodyModel?,
    val isDrinks : Type
){

enum class Type(val type: String, val value: Boolean) {
        NO("No", false),
        YES("Yes", true)
    }
}

BodyModel 类

data class BodyModel(
    val height: Int?,
    val weight: Int?
)

用户类

data class User(
    val id: String,
    val height: Int?,
    val isDrinks: Boolean?
){

@Ignore
fun toCustomer() = Customer(
    id, 
    BodyModel(height?:-1, -1 ),
    Customer.Type(?????????)
)

【问题讨论】:

  • Customer.Type.NOCustomer.Type.YES。但是为什么要使用枚举来表示本质上是布尔值呢?
  • @Tenfour04,我的服务器将isDrinks 作为Boolean 提供。我在具有枚举逻辑的 radioGroup 的 UI 中实现了这一点。我需要将isDrinks 传递给Customer.Type.YES or Customer.Type.NO

标签: android kotlin enums


【解决方案1】:

你可以这样做:

@Ignore
fun toCustomer() = Customer(
    id, 
    BodyModel(height?:-1, -1 ),
    if (isDrinks == true) Customer.Type.YES else Customer.Type.NO
)

【讨论】:

    【解决方案2】:

    如果这是一个玩具示例并且您想要更通用的东西,试试这个:

    enum class Type(val type: String, val value: Boolean) {
      NO("No", false),
      YES("Yes", true);
    
      companion object {
        val map: Map<Boolean, Type> = Type.values().associateBy{it.value}
      }
    }
    

    然后这样做

    fun toCustomer() = Customer(
        id, 
        BodyModel(height?:-1, -1 ),
        Customer.Type.map[isDrinks]
    )
    

    【讨论】:

    • 我已经在 Customer 类中有一个伴生对象。虽然你的回答很有帮助。
    猜你喜欢
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    • 2023-02-21
    • 1970-01-01
    • 2010-12-21
    相关资源
    最近更新 更多