Kotlin Set toBooleanArray()
Syntax & Examples


Set.toBooleanArray() extension function

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


Syntax of Set.toBooleanArray()

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

fun Collection<Boolean>.toBooleanArray(): BooleanArray

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

Return Type

Set.toBooleanArray() returns value of type BooleanArray.



✐ Examples

1 Converting a set of Boolean values to a BooleanArray

Using toBooleanArray() to convert a set of Boolean values to a BooleanArray.

For example,

  1. Create a set of Boolean values.
  2. Use toBooleanArray() to convert the set to a BooleanArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val booleanSet = setOf(true, false, true)
    val booleanArray = booleanSet.toBooleanArray()
    println(booleanArray.joinToString())
}

Output

true, false, true

2 Handling an empty set of Boolean values

Using toBooleanArray() to handle an empty set of Boolean values.

For example,

  1. Create an empty set of Boolean values.
  2. Use toBooleanArray() to convert the empty set to a BooleanArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val emptySet = emptySet<Boolean>()
    val booleanArray = emptySet.toBooleanArray()
    println(booleanArray.joinToString())
}

Output


3 Converting a set of mixed Boolean values to a BooleanArray

Using toBooleanArray() to convert a set of mixed Boolean values to a BooleanArray.

For example,

  1. Create a set of mixed Boolean values.
  2. Use toBooleanArray() to convert the set to a BooleanArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val mixedSet = setOf(true, false, true, false)
    val booleanArray = mixedSet.toBooleanArray()
    println(booleanArray.joinToString())
}

Output

true, false, true, false

Summary

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