Home > Software design >  Kotlin. How to reset each array element to zero?
Kotlin. How to reset each array element to zero?

Time:02-05

I'm using FloatArray:

  private val values = FloatArray(5)

At some point, I need to reset each array value to zero. I tried doing it like this:

  values.onEachIndexed { index, value -> value[index] = 0.0f  }

But I am getting this error

No set method providing array access

At the same time, this code works (outside onEachIndexed) and I can set the value for the element:

values[1] = 4.0f

What am I doing wrong ? Please help me

CodePudding user response:

Your attempt does not work because value there represents an element of the array, not the array itself, so you cannot use [] to set it. Reassigning it a new value will not work either, because value is a lambda parameter.

There is a builtin method for filling the entirety (or a portion) the array - fill

values.fill(0.0f)
  • Related