Kotlin Array.toBooleanArray()

Kotlin Array.toBooleanArray() Tutorial

The Array.toBooleanArray() function in Kotlin is used to convert an Array of primitive booleans into a BooleanArray. It creates a new BooleanArray object with the same elements as the original array.

This is just a conversion of data from Array<Boolean> type to BooleanArray type.

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

Syntax

The syntax of the toBooleanArray() function is as follows:

fun Array<out Boolean>.toBooleanArray(): BooleanArray

Examples for Array.toBooleanArray() function

1. Convert Array to BooleanArray

In this example, we’ll take an array of type Array<Boolean> with some initial values, and convert this array to a BooleanArray.

Kotlin Program

fun main() {
    val array: Array<Boolean> = arrayOf(true, false, false, false, true, false)

    // Using toBooleanArray() to convert the array to a boolean array
    val booleanArray = array.toBooleanArray()

    // Printing the original array and the resulting boolean array
    println("Array:\n${array.joinToString(", ")}\n")
    println("Boolean Array:\n${booleanArray.joinToString(", ")}")
}

Output

Numbers Array:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Boolean Array:
false, true, false, true, false, true, false, true, false, true

Summary

In this tutorial, we’ve covered the Array.toBooleanArray() function in Kotlin, its syntax, and how to use it to convert an Array of primitive booleans to a BooleanArray.