0

So i have this 2d array, and i want to copy it to another seperate variable. I have tried using System.arrayCopy and Array.copyOf, but both seem to just return a reference to the array i'm trying to copy, not a new array. Are there any buildt in methods for this, or do i have to make one myself?

Kris10an
  • 548
  • 3
  • 23

1 Answers1

1

Kotlin, like Java, doesn't really have multi-dimensional arrays.  What it does have is arrays of arrays.  So what you have is an array, each element of which is another array.  It looks like a 2-dimensional array most of the time, but you've found a case where it doesn't!

What functions like System.arrayCopy do is create a copy of the outer array; but it's a shallow copy, which still refers to the same inner arrays as the original.

What you want is a deep copy, which creates copies of all the inner arrays too.

See How to copy a two-dimensional array in Kotlin? or How do I do a deep copy of a 2d array in Java? for a few examples of that.

gidds
  • 16,558
  • 2
  • 19
  • 26