How to add an item to an ArrayList in Kotlin?

后端 未结 4 1401
半阙折子戏
半阙折子戏 2021-01-31 01:13

How to add an item to an ArrayList in Kotlin?

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-31 01:47

    If you have a MUTABLE collection:

    val list = mutableListOf(1, 2, 3)
    list += 4
    

    If you have an IMMUTABLE collection:

    var list = listOf(1, 2, 3)
    list += 4
    

    note that I use val for the mutable list to emphasize that the object is always the same, but its content changes.

    In case of the immutable list, you have to make it var. A new object is created by the += operator with the additional value.

提交回复
热议问题