https://kotlinlang.org logo
#compose
Title
# compose
u

ursus

03/10/2020, 3:21 AM
I wanted to ask folks bit of a OT but related to paradigm shift compose will bring, i.e. immutable models. I like this, but ergonomics are very poor imo, given a nested model like this
Copy code
data class State(
    val items: List<Item> = emptyList(),
    ...
)

sealed class Item
data class HeaderItem(val titleRes: Int) : Item()
sealed class ServiceItem : Item() { ..
data class SimpleItem(..) : ServiceItem
data class FormItem(val textItems: List<TextItem> = emptyList()) : ServiceItem
-- lets say now I need to change text item inside a form item with mutable models code is pretty neat in kotlin
Copy code
state.items
    .firstOrNull { it is FormItem && item.service.id == serviceId }
    ?.let { it as FormItem }
    ?.textItems
    ?.firstOrNull { it.id == textItemId }
    ?.apply {
        value = text
        validity = FormItem.TextItem.Validity.PENDING
    }
with immutable obviously you need to create copies
Copy code
setState {
    copy(
        items = items.map { item ->
            if (item is FormItem && item.service.id == serviceId) {
                item.copy(
                    textItems = item.textItems.map {
                        if (it.id == textItemId) {
                            it.copy(value = text, validity = FormItem.TextItem.Validity.PENDING)
                        } else {
                            it
                        }
                    })
            } else {
                item
            }
        }
    )
}
e

elizarov

03/10/2020, 8:14 AM
This is more a question for #general or for #language-evolution It will have to be address in future versions of Kotlin to make working with immutable data structures easier, not something specific to compose.
c

carbaj0

03/10/2020, 11:52 AM
you can look this for avoiding boilerplate https://arrow-kt.io/docs/optics/lens/
j

Javier Troconis

03/10/2020, 2:12 PM
+1 for optics. Not sure if the language will evolve to have something similar