Kotlin Set toIntArray()
Syntax & Examples


Set.toIntArray() extension function

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


Syntax of Set.toIntArray()

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

fun Collection<Int>.toIntArray(): IntArray

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

Return Type

Set.toIntArray() returns value of type IntArray.



✐ Examples

1 Converting a set of Int values to an IntArray

Using toIntArray() to convert a set of Int values to an IntArray.

For example,

  1. Create a set of Int values.
  2. Use toIntArray() to convert the set to an IntArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val intSet = setOf(1, 2, 3)
    val intArray = intSet.toIntArray()
    println(intArray.joinToString())
}

Output

1, 2, 3

2 Handling an empty set of Int values

Using toIntArray() to handle an empty set of Int values.

For example,

  1. Create an empty set of Int values.
  2. Use toIntArray() to convert the empty set to an IntArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val emptySet = emptySet<Int>()
    val intArray = emptySet.toIntArray()
    println(intArray.joinToString())
}

Output


3 Converting a set of mixed Int values to an IntArray

Using toIntArray() to convert a set of mixed Int values to an IntArray.

For example,

  1. Create a set of mixed Int values.
  2. Use toIntArray() to convert the set to an IntArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val mixedSet = setOf(1, -2, 3, -4)
    val intArray = mixedSet.toIntArray()
    println(intArray.joinToString())
}

Output

1, -2, 3, -4

Summary

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