Java 如何在没有初始化和特定数量元素的情况下在 Kotlin 中创建对象数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49592991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I create an array of objects in Kotlin without initialization and a specific number of elements?
提问by Eduardo Corona
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:
我想在 Kotlin 中创建一个具有特定数量元素的对象数组,问题是我现在没有声明中每个对象的初始化当前值,我尝试过:
var miArreglo = Array<Medico>(20, {null})
in Java, I have this and is exactly what I want, but i need it in Kotlin. :
在 Java 中,我有这个,这正是我想要的,但我在 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?
上面 Java 代码的 Kotlink 等价物是什么?
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"
但我 Android Studio 向我显示消息:“Val 无法重新分配”
采纳答案by creativecreatorormaybenot
The Kotlin equivalent of that could would be this:
Kotlin 的等价物可能是这样的:
val miArreglo = Array(20) { Medico() }
But I would strongly advice you to using Listsin 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:
但我强烈建议您在 Kotlin 中使用Lists,因为它们更加灵活。在你的情况下,List
不需要是可变的,因此我会建议这样的:
val miArreglo = List(20) { Medico() }
The two snippets above can be easily explained. The first parameter is obviouslythe 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.
上面的两个片段很容易解释。第一个参数显然是Java 中的Array
orList
大小,第二个参数是 lambda 函数,也就是init { ... }
函数。该init { ... }
函数可以由某种操作组成,最后一个值将始终是返回类型和返回值,即在这种情况下是一个Medico
对象。
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.
我还选择使用 aval
而不是 a,var
因为List
's 和Array
's 不应重新分配。如果你想编辑你的List
,请改用 a MutableList
。
val miArreglo = MutableList(20) { Medico() }
You can edit this list then, e.g.:
然后您可以编辑此列表,例如:
miArreglo.add(Medico())