Program to create Kotlin array of given elements with Example.
You can create kotlin array of given elements using –
1. Create Kotlin Array Using arrayOf() function –
We can use arrayOf() library function to create an array of given elements. For example,
val arr = arrayOf(1, 2, 3)
Above code creates an array of elements 1, 2 and 3 i.e. [1, 2, 3]
In other words,
If you want to use arrayOf() library function, you need to pass values of elements in array instead of just size.
Here, we created an array of 6 integer element 1, 2, 3, 4, 5 and 6.
val arr = arrayOf(1, 2, 3, 4, 5, 6)
Similarly, you can create an array of float as –
val arr = arrayOf(1.2f, 2.1f, 3.5f, 4.0f, 5.4f, 6.9f)
Other data types such as Double, Boolean, Char etc. can used to create array. You just need to pass values in arrayOf() library function.
1.1 Create array of objects using arrayOf()
If you have custom class and you want to create an array of objects, you can do so using arrayOf() function.
For example,
fun main() { val arr = arrayOf(CustomClass("Rohan"), CustomClass("Ram")) println("Elements in array: ") // Print each element in array. arr.forEach { println(it.name) } } class CustomClass(var name: String)
When you run above program, output will be –
Elements in array: Rohan Ram
2. Create Kotlin Array Using factory function
Each special class of primitive data type has a corresponding factory function that can be used to
create array. For example, IntArray class, for integer data type, has factory function intArrayOf() that can be used to create array. For example,
val arr = intArrayOf(1, 2, 3, 4, 5, 6, 7)
Note that you must pass values of elements to factory function to create array. You can n’t just pass size of array. If you have only size information, you can use IntArray(size) to create array of given size.
For example,
fun main() { val arr = intArrayOf(1, 2, 3, 4, 5) println("Elements in array: ") // Print each element in array. arr.forEach { println(it) } }
When you run the above program, output will be –
Elements in array: 1 2 3 4 5
Similarly, you can use other factory function as well.
Data type | Class | Factory Function |
Integer | IntArray | intArrayOf() |
Float | FloatArray | floatArrayOf() |
Double | DoubleArray | doubleArrayOf() |
Boolean | BooleanArray | booleanArrayOf() |
Char | CharArray | charArrayOf() |
Byte | ByteArray | byteArrayOf() |
Long | LongArray | longArrayOf() |
Short | ShortArray | shortArrayOf() |
Unsigned Int | UIntArray | uintArrayOf() |
Unsigned Byte | UByteArray | ubyteArrayOf() | Unsigned Short | UShortArray | ushortArrayOf() |