How to initialize an array in Kotlin with values?

前端 未结 20 2009
谎友^
谎友^ 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:14

    You can create an Int Array like this:

    val numbers = IntArray(5, { 10 * (it + 1) })
    

    5 is the Int Array size. the lambda function is the element init function. 'it' range in [0,4], plus 1 make range in [1,5]

    origin function is:

     /**
     * An array of ints. When targeting the JVM, instances of this class are 
     * represented as `int[]`.
     * @constructor Creates a new array of the specified [size], with all elements 
     *  initialized to zero.
     */
     public class IntArray(size: Int) {
           /**
            * Creates a new array of the specified [size], where each element is 
            * calculated by calling the specified
            * [init] function. The [init] function returns an array element given 
            * its index.
            */
          public inline constructor(size: Int, init: (Int) -> Int)
      ...
     }
    

    IntArray class defined in the Arrays.kt

    0 讨论(0)
  • 2020-12-22 21:16

    You can try this:

    var a = Array<Int>(5){0}
    
    0 讨论(0)
  • 2020-12-22 21:16

    In this way, you can initialize the int array in koltin.

     val values: IntArray = intArrayOf(1, 2, 3, 4, 5,6,7)
    
    0 讨论(0)
  • 2020-12-22 21:19

    Declare int array at global

    var numbers= intArrayOf()
    

    next onCreate method initialize your array with value

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //create your int array here
        numbers= intArrayOf(10,20,30,40,50)
    }
    
    0 讨论(0)
  • 2020-12-22 21:21

    Simple Way:

    For Integer:

    var number = arrayOf< Int> (10 , 20 , 30 , 40 ,50)

    Hold All data types

    var number = arrayOf(10 , "string value" , 10.5)

    0 讨论(0)
  • 2020-12-22 21:22

    Here's an example:

    fun main(args: Array<String>) {
        val arr = arrayOf(1, 2, 3);
        for (item in arr) {
            println(item);
        }
    }
    

    You can also use a playground to test language features.

    0 讨论(0)
提交回复
热议问题