How to clone object in Kotlin?

前端 未结 9 465
清歌不尽
清歌不尽 2020-12-09 07:04

The question is that simple.

Kotlin documentation describes cloning only in accessing Java and in enum class. In latter case clone is just throwing an exception.

9条回答
  •  情歌与酒
    2020-12-09 08:06

    A Kotlin data class is easy to clone using .copy()

    All values with be shallow copied, be sure to handle any list/array contents carefully.

    A useful feature of .copy() is the ability to change any of the values at copy time. With this class:

    data class MyData(
        val count: Int,
        val peanuts: Int?,
        val name: String
    )
    val data = MyData(1, null, "Monkey")
    

    You could set values for any of the properties

    val copy = data.copy(peanuts = 100, name = "Elephant")
    

    The result in copy would have values (1, 100, "Elephant")

提交回复
热议问题