英文:
How to change different attributes of an object with only one function method in kotlin?
问题
I can help with that. Here's the translation of the code portion:
我有三个文本字段,用于输入姓名、年龄和性别,并使用一个 uiState 数据类来保存输入的状态:
data class UiState(
val nameInput: String = "",
val ageInput: String = "",
val genderInput: String = "",
)
为了更新状态,我使用以下函数来处理文本字段的 onValueChanged 函数(每个属性都有一个函数:姓名、年龄和性别):
```kotlin
fun updateInput(input: String, attribute: String) {
_uiState.update {
when (attribute) {
"nameInput" -> it.copy(nameInput = input)
"ageInput" -> it.copy(ageInput = input)
"genderInput" -> it.copy(genderInput = input)
else -> it
}
}
}
现在,您可以使用一个函数来更新这三个文本字段中的任何一个。感谢您的提问。
Please note that I've combined the three functions into one by introducing an "attribute" parameter to specify which input field you want to update.
<details>
<summary>英文:</summary>
I have 3 textFields for name, age and gender in compose and use a uiState data class to hold the states of the inputs:
data class UiState(
val nameInput: String = "",
val ageInput: String = "",
val genderInput: String = "",
)
To update the states I use the following functions for the onValueChanged function (one function for each attribute: name, age and gender) of the textfields:
fun updateNameInput(input: String) {
_uiState.update { it.copy(nameInput = input) }
}
fun updateAgeInput(input: String) {
_uiState.update { it.copy(ageInput = input) }
}
fun updateGenderInput(input: String) {
_uiState.update { it.copy(genderInput = input) }
}
Now my question is, how can I boil those 3 functions into one and pass in the argument (eighter nameInput, ageInput or genderInput) in the function definition and update only that argument.
I want to be able to use only one function to be used to update eighter of those 3 textfields.
Thanks in advance.
</details>
# 答案1
**得分**: 1
以下是已翻译的代码部分:
```kotlin
要将它放入一个函数中,我想你可以使函数参数变为可选,并为那些非空的参数创建新的副本。然后,您可以使用空默认参数使它们变为可选。
fun updateNonNullInput(name: String? = null, age: String? = null, gender: String? = null) {
_uiState.update {
var value = it
if (name != null) value = value.copy(nameInput = name)
if (age != null) value = value.copy(ageInput = age)
if (gender != null) value = value.copy(genderInput = gender)
value
}
}
(注意:我已经去掉了 "To put it in one function, I suppose you could" 这一句,因为它不是代码的一部分。)
英文:
To put it in one function, I suppose you could make the function parameters optional and create new copies for the ones that are non-null. Then you can make null default arguments to allow them to be optional.
fun updateNonNullInput(name: String? = null, age: String? = null, gender: String? = null) {
_uiState.update {
var value = it
if (name != null) value = value.copy(nameInput = name)
if (age != null) value = value.copy(ageInput = age)
if (gender != null) value = value.copy(genderInput = gender)
value
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论