[英]Android Kotlin convert data class into enum class
這里Customer
和BodyModel
是數據類。 我需要一個內部 function 在User
, toCustomer()
,將User class
轉換為Customer class
。 我被困在將Boolean type
更改為Customer.Type
客戶 Class
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)
}
}
車身型號 class
data class BodyModel(
val height: Int?,
val weight: Int?
)
用戶 class
data class User(
val id: String,
val height: Int?,
val isDrinks: Boolean?
){
@Ignore
fun toCustomer() = Customer(
id,
BodyModel(height?:-1, -1 ),
Customer.Type(?????????)
)
你可以這樣做:
@Ignore
fun toCustomer() = Customer(
id,
BodyModel(height?:-1, -1 ),
if (isDrinks == true) Customer.Type.YES else Customer.Type.NO
)
如果這是一個玩具示例並且您想要更通用的東西,請嘗試以下操作:
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]
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.