我有一个场景。我在Kotlin中创建了一个数据类,如下所示:
data class AgentDetails(
val mobileNo: String,
val Name: String,
val Email: String,
val Password: String,
val Occupation: String,
val pincode: String,
val usertype: String,
val profilepic: String,
val AccountStatus: String
)
我想将此数据类的不同类型的对象发送到Web服务:
第一个对象示例:
val agentDetails = AgentDetails(mobileNo = mobileNumberText.text.toString(),
Name = userNameText.text.toString(),
Email = emailIdText.text.toString(),
Password = HashUtils.sha1(passwordText.text.toString()),
Occupation = item,
pincode = pinCodeText.text.toString(),
usertype = "Agent",
profilepic = "null", AccountStatus = "pending")
在第二个对象中我只想发送手机号码。我不想包括任何其他领域。像这样:
val agentDetails = AgentDetails(mobileNo = mobileNumberText.text.toString())
在第3个对象中,我只想发送电子邮件ID。而不是创建多个数据类。我可以为多个实现使用相同的数据类吗?
答案 0 :(得分:1)
最简单的方法是使字段可以为空并提供默认值:
data class AgentDetails(
val mobileNo: String? = null,
val Name: String? = null,
val Email: String? = null,
val Password: String? = null,
val Occupation: String? = null,
val pincode: String? = null,
val usertype: String? = null,
val profilepic: String? = null,
val AccountStatus: String? = null
)
答案 1 :(得分:1)
就个人而言,我定义了三个对象,因为它们代表三个不同的概念(或概念的投影)。但是如果你使你的属性可以为空并提供一个默认值null,你可以随意创建它们......
data class AgentDetails(
val mobileNo: String? = null,
val name: String? = null,
val email: String? = null,
val password: String? = null,
val occupation: String? = null,
val pincode: String? = null,
val usertype: String? = null,
val profilepic: String? = null,
val accountStatus: String? = null
)
注意:我已经将一些属性名称更改为camelCase,这是正确的约定。这一切都很好:
AgentDetails(mobileNo = mobileNumberText.text.toString())
AgentDetails(email = "foo@example.com")
AgentDetails(name = "Foo", password = "Bar")
未提供的所有其他字段都将为null,并且类型将为可空,因此您必须防范它。否则,我为此定义了三个数据类。
另一种解决方案是考虑密封的类结构:
sealed class AgentDetails
data class AgentByName(val name: String) : AgentDetails()
data class AgentByEmail(val email: String): AgentDetails()
// etc..
然后在when
表达式中使用它:
fun doSomethingWithAgents(agentDetails: AgentDetails) {
when (agentDetails) {
is AgentByName -> // Do something
is AgentByEmail -> // Do Something
}
}