What is the intArrayOf() method in Kotlin?

Overview

The intArrayOf() function in Kotlin creates a new array that can hold integer elements.

By providing the integer values as arguments, we can also pass the elements to be included in the array.

Syntax

fun intArrayOf(vararg elements: Int): IntArray

Parameter

This method takes the integer elements to be included in the array as an argument. The argument is of a variable type. So, we can pass any number of integer elements.

Return value

The intArrayOf() function in Kotlin returns a new IntArray containing the provided integer numbers that are passed as arguments.

Code

The code below demonstrates how to use the intArrayOf() method in Kotlin:

fun main() {
val intArray = intArrayOf(1,2,3,4,5);
print("intArray is: ");
println(intArray.joinToString(" "));
val emptyIntArray = intArrayOf();
print("emptyIntArray is: ");
println(emptyIntArray.joinToString(" "));
}

Explanation

  • Line 2: We use the intArrayOf() method with 1, 2, 3, 4, and5 as arguments. This method returns a new IntArray with 1, 2, 3, 4, and 5 as the elements of the array.

  • Line 4: We use the joinToString() method to convert the array into a string. Then, we print it.

  • Line 6: We use the intArrayOf() method with no arguments. This method returns a new empty IntArray.

Free Resources