Nexon
Nexon

Reputation: 326

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

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?

Upvotes: 1

Views: 1767

Answers (2)

Adam Millerchip
Adam Millerchip

Reputation: 23091

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] }

Upvotes: 3

baltekg
baltekg

Reputation: 1223

You cannot write that but instead you can do:

val y = x.toFloatArray()

Upvotes: 5

Related Questions