乐闻世界logo
搜索文章和话题

How to Initialize Arrays with Values in Kotlin?

2月7日 13:21

In Kotlin, you can use various methods to initialize arrays with specific values. Here are some common approaches:

  1. Using the arrayOf function: This is the most straightforward approach, where you can list all elements directly within the arrayOf function.

    kotlin
    val numbers = arrayOf(1, 2, 3, 4, 5)
  2. Using factory functions, such as the Array constructor: If you want to initialize an array with a specific size and values computed by a lambda expression, you can use the Array constructor. This requires the array size and a lambda expression that defines how to compute each element's value.

    kotlin
    val size = 5 val defaultValue = 10 val array = Array(size) { defaultValue }
  3. Using specific type arrays like IntArray, DoubleArray, etc.: For primitive types, Kotlin provides specific array types such as IntArray, DoubleArray, etc. These can also be initialized using similar factory methods.

    kotlin
    val intArray = IntArray(5) { 42 } // Creates an IntArray of size 5 with all elements initialized to 42

These methods can be used to initialize arrays with fixed values or dynamically computed values.

标签:Kotlin