Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin data class copy with changed var value

Tags:

kotlin

Why can't you copy data class object with var value change?

data class AppState(var list: List<Image> = ArrayList<Image>(),
                val uiState: UIState = UIState.LIST,
                val isFetching: Boolean = false)

...

val list = state!!.list.sublist(0,1);
state.copy(list = list)        // No change
state.copy(isFetching = true)  // Works like a charm
like image 247
aleien Avatar asked Dec 14 '22 05:12

aleien


1 Answers

The copy method does not mutate the original object. It returns a new object with the changed values. I tried your example, and both of your copies work as expected when I capture the returned object in a new val:

val list = state!!.list.subList(0,1)

// Creates a new object with the new list.
val withNewList = state.copy(list = list)

// Creates a new object with the new isFetching.
val withNewIsFetching = withNewList.copy(isFetching = true)

If you want to mutate the list-value of your state-object, you can just do this:

val list = state!!.list.subList(0,1)
state.list = list
like image 105
marstran Avatar answered Jan 04 '23 15:01

marstran