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"

推荐答案

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() }

以上两个片段很容易解释.第一个参数是obviously,即Java中的ArrayList大小,第二个是lambda函数,即init { ... }函数.init { ... }函数可以由某种操作组成,最后一个值始终是返回类型和返回值,即在本例中是Medico对象.

我还 Select 使用val而不是var,因为ListArray不应该重新分配.如果您想编辑您的List,请改用MutableList.

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

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

miArreglo.add(Medico())

Kotlin相关问答推荐

Scala与Kotlin中的迭代

Kotlin Poet 的导入不明确

从 Kotlin 的父类获取函数注解

如何优雅地声明一个StateFlow?

限制通用Kotlin枚举为特定类型

gradle 如何 Select 以-jvm结尾的库?

kotlin 单例异常是好是坏?

TestContainers PostgreSQLContainer 与 Kotlin 单元测试:Not enough information to infer type variable SELF

Kotlin RxJava 可空的错误

下拉通知面板时是否可以暂停Android中的任何视频(媒体播放器)应用程序?

Kotlin 中 lambda 表达式中的默认参数

在 Kotlin 中实现 (/inherit/~extend) 注解

将协同路由调用放在存储库或ViewModel中哪个更好?

kotlin-bom 库是做什么的?

Kotlin reflect proguard SmallSortedMap

Java中lazy的Kotlin类似功能是什么?

Mocked suspend函数在Mockito中返回null

不推荐使用仅限生命周期的LifecycleEvent

我应该在哪里调用 MobileAds.initialize()?

Kotlin:访问 when 语句的参数