Best collection to use for the folllowing

Hi there, I am having difficulty understanding which collection I should use. I want to be able to store data in a 2D mutable array and have the array expand dynamically to fit new data. The collection needs to fill any empty spaces with null objects as the data will not be consecutive in location. Also, I need it so that the collection can have negative indexes with the initial data value at [0][0]. Will I need to write a custom collection? This is in the context of a game where “tile” objects need to be stored in a grid structure and added dynamically.

The question is not about Kotlin.
What you need is not a collection, but a spreadsheet. There are a lot of different ways to implement it depending on specific task and optimizations you need. I can give you only the very basic example.

class SpreadSheet<T>{
  private data class Index(val i: Int, val j:Int)

  private val data = HashMap<Index,T>()

  operator fun get(i: Int, j:Int) = data[Intex(i,j)]
  operator fun set(i: Int, j: Int, value: T?){
    data[Index(i,j)] = value


1 Like

Perfect, that’s exactly the sort of thing I was looking for, thanks. Yeah sorry the question isn’t directly related to Kotlin itself but I was wondering if Kotlin had anything like this built in and I am working in Kotlin.

Kotlin gives you get and set operator overloading to make it beautiful and data class hash code to make it compact.

1 Like