我有一个场景。我在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")
在第二个对象中,我只想发送手机号码。我不想包括任何其他 Realm 。像这样:
val agentDetails = AgentDetails(mobileNo = mobileNumberText.text.toString())
在第三个对象中,我只想发送电子邮件ID。而不是创建多个数据类。我可以将同一数据类用于多种实现吗?
最佳答案
就个人而言,我将定义三个对象,因为它们代表了三个不同的概念(或一个概念的投影)。但是,如果将属性设置为可空并提供默认值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 = "[email protected]")
AgentDetails(name = "Foo", password = "Bar")
所有其他未提供的字段将为空,并且类型将为可空,因此您必须避免这种情况。否则,我将为此定义三个数据类。
另一个解决方案是考虑密封的类结构:
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
}
}
关于android - 自定义单个数据类而无需在Kotlin中创建多个数据类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49468187/