Kotlin Array.toFloatArray()

Kotlin Array.toFloatArray() Tutorial

The Array.toFloatArray() function in Kotlin is used to convert an Array of Float type values, into a FloatArray. It creates a new FloatArray containing the elements of the given original array.

This is just a conversion of data from Array<Float> type to FloatArray type.

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

Syntax

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

fun Array<out Float>.toFloatArray(): FloatArray

Examples for Array.toFloatArray() function

1. Convert Array of floating point values to FloatArray

In this example, we’ll take an array of floating point numbers in originalArray, and convert this Array into an FloatArray using Array.toFloatArray().

Kotlin Program

fun main() {
    val originalArray: Array<Float> = arrayOf(3.14f, 1.732f, 1.024f, 0.12f)

    // Using toFloatArray() to convert the Array of floating point numbers to a FloatArray
    val floatArray = originalArray.toFloatArray()

    // Printing the original array and the resulting FloatArray
    println("Given Array:\n${originalArray.contentToString()}\n")
    println("Float Array:\n${floatArray.contentToString()}")
}

Output

Given Array:
[3.14, 1.732, 1.024, 0.12]

Float Array:
[3.14, 1.732, 1.024, 0.12]

Summary

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