How to clone object in Kotlin?

前端 未结 9 473
清歌不尽
清歌不尽 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:01

    Here is a consistent solution that works for any object type:

    Kotlin's Array data structure provides a clone() method that can be used to clone the contents of the array:

    val a = arrayOf(1)
    //Prints one object reference
    println(a)     
    //Prints a different object reference
    println(a.clone())
    

    As of Kotlin 1.3, the clone method has been supported on all major targets, so it should be usable across platforms.

提交回复
热议问题