Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to create FloatArray in Kotlin

Tags:

kotlin

val matrix: FloatArray = emptyArray<Float>().toFloatArray()

This definitely works, it just looks pretty ugly. Is there no method to create XXXArray directly? Did I miss something?

like image 541
Louis Tsai Avatar asked Oct 09 '18 15:10

Louis Tsai


1 Answers

You have three options for creating a FloatArray:

val arr1 = floatArrayOf(.1f)
val arr2 = FloatArray(12)

And, as you are doing already, emptyArray.

floatArrayOf works exactly like you'd expect; creates an array of the items with a corresponding size. It works just like arrayOf, just with a different return type.

The second one creates one defined by size. I just set the size to 12 as a demo, but you get the idea. The second one is roughly equivalent to float[] arr2 = new float[12];.

By default, it sets all the values to 0, but you can customize that with FloatArray(12) { 1f }, where 1f can be any number you want to initialize all the items in the array as. You don't need that if you just want to set it to 0 though.

like image 89
Zoe stands with Ukraine Avatar answered Sep 24 '22 22:09

Zoe stands with Ukraine