Search code examples
javalistkotlinarraylistclone

Is there an easy way for deep cloning a list in Kotlin?


I need to clone an ArrayList of type Any which contains only strings and Arraylists that contain only strings and arrayLists that ... . A shallow copy does not work for me as I need to have every element cloned. My idea is to loop through every element or to convert the ArrayList to a String and than back to an ArrayList ( using the commas and brackets in the string). Any idea how to do this easier? ( Java answers are appreciated too as I think it is convertable to Kotlin)


Solution

  • fun cloned(arrayList: ArrayList<Any>): ArrayList<Any> {
      return arrayList.map {
        when (it) {
          is ArrayList<*> -> cloned(it.toList() as ArrayList<Any>)
          else            -> it
        }
      } as ArrayList<Any>
    }