2016-06-14 56 views
0

爲什麼不能複製具有var值更改的數據類對象?更改var值的Kotlin數據類複製

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 
+2

你知道'copy'返回一個新的實例,並且不修改接收者? – nhaarman

回答

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 -object的列表值,你可以做這個:

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

此外,你應該做'val list = state?.list?.subList(0,1)?:emptyList()',而不是使用'!!'操作符來避免NullPointerExceptions。 – marstran