具有更改的var值的Kotlin数据类副本

时间:2016-06-14 20:25:35

标签: kotlin

为什么不能使用var值更改来复制数据类对象?

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

1 个答案:

答案 0 :(得分:6)

copy方法不会改变原始对象。它返回一个具有更改值的新对象。我尝试了您的示例,当我在新的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)

如果要改变state - 对象的列表值,可以这样做:

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