0

How I can create Array of my custom objects with fixed size in Kotlin?

like?

ArrayList<CustomObject> array = new ArrayList<>()

or ?

CustomObject[] objects = new CustomObjects[5]

1 Answer 1

3

There are two options:

  • arrayOfNulls(size: Int) - creates an array of a specific size and populates it will null references. It's not possible to use this function with non-nullable types.
  • <init>(size: Int, init: (Int) -> T) constructor - creates an array of a specific size and runs supplied lambda for every index in the array to create an element for that index.
Sign up to request clarification or add additional context in comments.

1 Comment

private val customObjectArray = arrayOfNulls<customObject>(5) customObjectArray[0] = CustomObject(this, 2)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.