Kotlin Tutorials

Kotlin Set toFloatArray()
Syntax & Examples

Set.toFloatArray() extension function

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


Syntax of Set.toFloatArray()

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

fun Collection<Float>.toFloatArray(): FloatArray

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

Return Type

Set.toFloatArray() returns value of type FloatArray.



✐ Examples

1 Converting a set of Float values to a FloatArray

Using toFloatArray() to convert a set of Float values to a FloatArray.

For example,

  1. Create a set of Float values.
  2. Use toFloatArray() to convert the set to a FloatArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val floatSet = setOf(1.1f, 2.2f, 3.3f)
    val floatArray = floatSet.toFloatArray()
    println(floatArray.joinToString())
}

Output

1.1, 2.2, 3.3

2 Handling an empty set of Float values

Using toFloatArray() to handle an empty set of Float values.

For example,

  1. Create an empty set of Float values.
  2. Use toFloatArray() to convert the empty set to a FloatArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val emptySet = emptySet<Float>()
    val floatArray = emptySet.toFloatArray()
    println(floatArray.joinToString())
}

Output


3 Converting a set of mixed Float values to a FloatArray

Using toFloatArray() to convert a set of mixed Float values to a FloatArray.

For example,

  1. Create a set of mixed Float values.
  2. Use toFloatArray() to convert the set to a FloatArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val mixedSet = setOf(1.1f, -2.2f, 3.3f, -4.4f)
    val floatArray = mixedSet.toFloatArray()
    println(floatArray.joinToString())
}

Output

1.1, -2.2, 3.3, -4.4

Summary

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