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,
- Create a set of Float values.
- Use toFloatArray() to convert the set to a FloatArray.
- 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,
- Create an empty set of Float values.
- Use toFloatArray() to convert the empty set to a FloatArray.
- 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,
- Create a set of mixed Float values.
- Use toFloatArray() to convert the set to a FloatArray.
- 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.