33

I want to create an Array of objects with a specific number of elements in Kotlin, the problem is I don't now the current values for initialization of every object in the declaration, I tried:

var miArreglo = Array<Medico>(20, {null})

in Java, I have this and is exactly what I want, but i need it in Kotlin. :

Medico[] medicos = new Medico[20];

for(int i = 0 ; i < medicos.length; i++){
    medicos[i] = new Medico();

}

What would be the Kotlink equivalent of the above Java code?

Also, I tried with:

var misDoctores = arrayOfNulls<medic>(20)

for(i in misDoctores ){
    i = medic()
}

But I Android Studio show me the message: "Val cannot be reassigned"

1
  • If you don't know the current values, you are better off using a List instead, then you can just add the values as you go along. Also, you can find out the size of the list. In your case, the problem was i is declared as val, so you can't re-assign. Commented Dec 9, 2021 at 16:27

2 Answers 2

36

The Kotlin equivalent of that could would be this:

val miArreglo = Array(20) { Medico() }

But I would strongly advice you to using Lists in Kotlin because they are way more flexible. In your case the List would not need to be mutable and thus I would advice something like this:

val miArreglo = List(20) { Medico() }

The two snippets above can be easily explained. The first parameter is obviously the Array or List size as in Java and the second is a lambda function, which is the init { ... } function. The init { ... } function can consist of some kind of operation and the last value will always be the return type and the returned value, i.e. in this case a Medico object.

I also chose to use a val instead of a var because List's and Array's should not be reassigned. If you want to edit your List, please use a MutableList instead.

val miArreglo = MutableList(20) { Medico() }

You can edit this list then, e.g.:

miArreglo.add(Medico())
Sign up to request clarification or add additional context in comments.

2 Comments

You can also pass id parameter: List(20) { id -> Medico() }
how to use list in kotlin without size given? here its given as 20.
5

If you want list of nullable objects, we can do something like this

val fragment : Array<Fragment?> = Array(4) { null }


1 Comment

This is the equivalent to the question since in Java, an array can contain a null value.

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.