1

I basically wanted to create 2D array whose size is known to me on runtime

I have declare and array of LongArray as below

private lateinit var optionalGroup: Array<LongArray>

And I can assign value to it as below where group is my Mutable Map

 group.forEach { (key, value) -> optionalGroup[key - 1] = LongArray(value) }

My question is how can I initialize optionalGroup with size as of group ? I tried

`optionalGroup = Array(group.size)

thows error No value passed for parameter 'init'`

1
  • To create an array you need to pass the initial values of the array. Array(group.size) { LongArray(0) } should work, but you will also overwrite all the values later. Consider using a MutableList instead. Commented Feb 12, 2019 at 11:44

1 Answer 1

2

If you use an array, you have no choice but to initialize the initial values of each element

optionalGroup = Array(group.size) { LongArray(0) }

I suggest you use a mutable list instead to avoid having to initialize the elements:

private lateinit var optionalGroup: MutableList<LongArray>
optionalGroup = mutableListOf()

If this is not an option, you can still use a temporary mutable list and convert it back to a typed array:

val tempList = mutableListOf<LongArray>()
group.forEach { (key, value) -> tempList[key - 1] = LongArray(value) }
optionalGroup = tempList.toTypedArray()
Sign up to request clarification or add additional context in comments.

1 Comment

Generally you should avoid arrays and use lists whenever possible ;)

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.