如何通过在Kotlin中提供大小来创建数组

时间:2019-01-19 21:45:40

标签: android kotlin

我在Java中具有以下方法,并且在我的代码中运行良好。但是我只想将我的活动重写为kotlin。 我的Java方法:

private void testFunction() {
    ImageView[] pics;
    int count = 6;

    pics = new ImageView[count];
}

通过在Android Studio中自动进行转换,会产生以下乐趣,但会出现错误:

private fun testFunction() {
    val pics: Array<ImageView>
    val count = 6

    pics = arrayOfNulls(count)
}

如何归档相同的结果?

错误

enter image description here

2 个答案:

答案 0 :(得分:1)

private fun testFunction() {
    val pics: Array<ImageView?> = arrayOfNulls(6)

    // TODO the rest of your test
}

答案 1 :(得分:1)

或更短:

val pics = arrayOfNulls<ImageView?>(6)

这利用了Kotlin的类型推断的优势,并避免了冗余。