Kotlin Array.toIntArray()

Kotlin Array.toIntArray() Tutorial

The Array.toIntArray() function in Kotlin is used to convert an Array of Int type values, into an IntArray. It creates a new IntArray containing the elements of the original array.

This is just a conversion of data from Array<Int> type to IntArray type.

This tutorial will explore the syntax of the Array.toIntArray() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.toIntArray() function is as follows:

fun Array<out Int>.toIntArray(): IntArray

Examples for Array.toIntArray() function

1. Convert Array of integers to IntArray

In this example, we’ll take an array of integers in originalArray, and convert this Array into an IntArray using Array.toIntArray().

Kotlin Program

fun main() {
    val originalArray: Array<Int> = arrayOf(10, 20, 30, 40)

    // Using toIntArray() to convert the Array of integers to an IntArray
    val intArray = originalArray.toIntArray()

    // Printing the original array and the resulting IntArray
    println("Given Array:\n${originalArray.contentToString()}\n")
    println("Int Array:\n${intArray.contentToString()}")
}

Output

Given Array:
[10, 20, 30, 40]

Int Array:
[10, 20, 30, 40]

Summary

In this tutorial, we’ve covered the Array.toIntArray() function in Kotlin, its syntax, and how to use it to convert an Array of Int values into an IntArray.