In Kotlin, you can use various methods to initialize arrays with specific values. Here are some common approaches:
-
Using the
arrayOffunction: This is the most straightforward approach, where you can list all elements directly within thearrayOffunction.kotlinval numbers = arrayOf(1, 2, 3, 4, 5) -
Using factory functions, such as the
Arrayconstructor: If you want to initialize an array with a specific size and values computed by a lambda expression, you can use theArrayconstructor. This requires the array size and a lambda expression that defines how to compute each element's value.kotlinval size = 5 val defaultValue = 10 val array = Array(size) { defaultValue } -
Using specific type arrays like
IntArray,DoubleArray, etc.: For primitive types, Kotlin provides specific array types such asIntArray,DoubleArray, etc. These can also be initialized using similar factory methods.kotlinval 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.