How to clone object in Kotlin?

前端 未结 9 457
清歌不尽
清歌不尽 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 07:47

    If the class you are trying to clone does not implement Cloneable or is not a data class and is a part of an outside library, you can create an extension method that returns a new instance. For example:

    class Person {
      var id: String? = null
      var name: String? = null
    } 
    fun Person.clone(): Person {
      val person = Person()
      person.id = id
      person.name = name
      return person 
    }
    

提交回复
热议问题