Creating a FloatArray from an Array<Float> object in Kotlin

Viewed 630

I am trying to convert a Array object to a FloatArray using a spread operator:

val x = arrayOf(0.2f, 0.3f)
val y = floatArrayOf(*x)

Unfortunetly I get Type mismatch: inferred type is Array<Float> but FloatArray was expected

Why is there an error and how to make this work?

2 Answers

You cannot write that but instead you can do:

val y = x.toFloatArray()

toFloatArray is the obvious choice, but if for some reason you wanted to create a new float array without calling that, you could do the same thing it does internally: call the FloatArray constructor:

val x = arrayOf(0.2f, 0.3f)
val y = FloatArray(x.size) { x[it] }
Related