有一个数据类:
data class LoginResponse(
val accost: String? = null,
val name: String? = null,
val fullname: String? = null,
)
类中的数据来自服务,字段是可选的。任务是检查所有字段是否为空,如果该字段不为空且不为空,则将其分配给一个变量:
var accost = "друг"
该变量稍后将用于问候用户。目前实现如下:
if(!LoginResponse.accost.isNullOrEmpty())
accost = LoginResponse.data.accost
else if (!LoginResponse.name.isNullOrEmpty())
accost = LoginResponse.data.name
else if(!LoginResponse.fullname.isNullOrEmpty())
accost = LoginResponse.data.fullname
Toast.makeText("$accost", Toast.LENGTH_LONG).show()
数据类中的字段其实蛮多的,我想得到一个更漂亮、更易读的代码。
Kotlin 有一个很棒的 operator when(условие),是否有可能以某种方式将其应用于这种情况?
1 个回答