代码之家  ›  专栏  ›  技术社区  ›  Bryan

有没有办法从范围中创建非空数组?

  •  6
  • Bryan  · 技术社区  · 9 年前

    ImageButton[] buttons = new ImageButton[count];
    
    for (int i = 0; i < count; i++) {
       buttons[i] = view.findViewById(BUTTON_IDS[i]);
    }
    

    对Kotlin的简单转换产生以下结果:

    val buttons = arrayOfNulls<ImageButton>(count)
    
    for (i in 0..count) {
        buttons[i] = view.findViewById<ImageButton>(BUTTON_IDS[i])
    }
    

    ? 操作员。

    有没有办法以类似的方式创建数组,但不使用可选类型?

    1 回复  |  直到 9 年前
        1
  •  10
  •   hotkey    9 年前

    是的,使用 constructor of Array :

    val buttons = Array(count) { view.findViewById<ImageButton>(BUTTON_IDS[it])!! }
    
    推荐文章