How to initialize an array in Kotlin with values?

前端 未结 20 2008
谎友^
谎友^ 2020-12-22 21:03

In Java an array can be initialized such as:

int numbers[] = new int[] {10, 20, 30, 40, 50}

How does Kotlin\'s array initialization look li

相关标签:
20条回答
  • 2020-12-22 21:31

    My answer complements @maroun these are some ways to initialize an array:

    Use an array

    val numbers = arrayOf(1,2,3,4,5)
    

    Use a strict array

    val numbers = intArrayOf(1,2,3,4,5)
    

    Mix types of matrices

    val numbers = arrayOf(1,2,3.0,4f)
    

    Nesting arrays

    val numbersInitials = intArrayOf(1,2,3,4,5)
    val numbers = arrayOf(numbersInitials, arrayOf(6,7,8,9,10))
    

    Ability to start with dynamic code

    val numbers = Array(5){ it*2}
    
    0 讨论(0)
  • 2020-12-22 21:32

    Kotlin language has specialised classes for representing arrays of primitive types without boxing overhead: for instance – IntArray, ShortArray, ByteArray, etc. I need to say that these classes have no inheritance relation to the parent Array class, but they have the same set of methods and properties. Each of them also has a corresponding factory function. So, to initialise an array with values in Kotlin you just need to type this:

    val myArr: IntArray = intArrayOf(10, 20, 30, 40, 50)
    

    ...or this way:

    val myArr = Array<Int>(5, { i -> ((i+1) * 10) })
    
    myArr.forEach { println(it) }                                // 10, 20, 30, 40, 50
    

    Now you can use it:

    myArr[0] = (myArr[1] + myArr[2]) - myArr[3]
    
    0 讨论(0)
提交回复
热议问题