How can I create an array of objects in Kotlin without initialization and a specific number of elements?
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())
If you want list of nullable objects, we can do something like this
val fragment : Array<Fragment?> = Array(4) { null }