Kotlin Set toCharArray()
Syntax & Examples


Set.toCharArray() extension function

The toCharArray() extension function in Kotlin returns an array of Char containing all of the elements of the collection.


Syntax of Set.toCharArray()

The syntax of Set.toCharArray() extension function is:

fun Collection<Char>.toCharArray(): CharArray

This toCharArray() extension function of Set returns an array of Char containing all of the elements of this collection.

Return Type

Set.toCharArray() returns value of type CharArray.



✐ Examples

1 Converting a set of Char values to a CharArray

Using toCharArray() to convert a set of Char values to a CharArray.

For example,

  1. Create a set of Char values.
  2. Use toCharArray() to convert the set to a CharArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val charSet = setOf('a', 'b', 'c')
    val charArray = charSet.toCharArray()
    println(charArray.joinToString())
}

Output

a, b, c

2 Handling an empty set of Char values

Using toCharArray() to handle an empty set of Char values.

For example,

  1. Create an empty set of Char values.
  2. Use toCharArray() to convert the empty set to a CharArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val emptySet = emptySet<Char>()
    val charArray = emptySet.toCharArray()
    println(charArray.joinToString())
}

Output


3 Converting a set of mixed Char values to a CharArray

Using toCharArray() to convert a set of mixed Char values to a CharArray.

For example,

  1. Create a set of mixed Char values.
  2. Use toCharArray() to convert the set to a CharArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val mixedSet = setOf('x', 'y', 'z', 'a')
    val charArray = mixedSet.toCharArray()
    println(charArray.joinToString())
}

Output

x, y, z, a

Summary

In this Kotlin tutorial, we learned about toCharArray() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.