0
\$\begingroup\$

I don't like my current code, because of duplications. What's the best way to leverage Kotlin to make it more concise. I have simple registration form

data class RegisterForm @JvmOverloads constructor(
        val email: String = "",
        val emailError: String = "",

        val lastName: String = "",
        val lastNameError: String = "",

        ...
)

In my ViewModel I'm reacting to my TextWatcher. I set my state by updating my RegisterForm data class

fun onEmailChanged(email: String) {
    setState {
        copy(registerForm = registerForm
                .copy(email = email, emailError = validateEmail(email))
        ) }
}

fun onFirstNameChanged(text: String) {
    setState {
        copy(registerForm = registerForm
                .copy(firstName = text, firstNameError = validateFirstName(text))
        ) }
}

As you can see, I need to copy paste the code in my ViewModel every time I'm adding the new input field. How can I leverage Kotlin to get rid of these duplications?

\$\endgroup\$
2
\$\begingroup\$

In functional programming terms, using Lenses could help you modify nested object elegantly. There are no native supported lenses in kotlin language but some libraries provided. Check klenses or arrow.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.