从 Kotlin 中的 Array<Float> 对象创建 FloatArray

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

我正在尝试使用展开运算符将 Array 对象转换为 FloatArray:

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

不幸的是我得到类型不匹配:inferred type is Array<Float> but FloatArray was expected

为什么会出现错误以及如何让它工作?

你不能这样写,但你可以这样做:

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