Kotlin Array.toCharArray()

Kotlin Array.toCharArray() Tutorial

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

This is just a conversion of data from Array<Char> type to CharArray type.

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

Syntax

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

fun Array<out Char>.toCharArray(): CharArray

Examples for Array.toCharArray() function

1. Convert Array of characters to CharArray

In this example, we’ll take an array of characters in originalArray, and convert this Array into a CharArray using Array.toCharArray().

Kotlin Program

fun main() {
    val originalArray: Array<Char> = arrayOf('A', 'B', 'C', 'D')

    // Using toCharArray() to convert the Array of characters to a CharArray
    val charArray = originalArray.toCharArray()

    // Printing the original array and the resulting CharArray
    println("Given Array:\n${originalArray.contentToString()}\n")
    println("Char Array:\n${charArray.contentToString()}")
}

Output

Given Array:
[A, B, C, D]

Char Array:
[A, B, C, D]

Summary

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