Home > Mobile >  Array of array double won't adding a new element in kotlin
Array of array double won't adding a new element in kotlin

Time:11-27

I have array of array double but it won't add element after using .plusElementor .plus. code below inside from view model that returns it.data which is a list of object

Code

var ageEntry : Int
val dataObject : Array<Array<Double>> = arrayOf()
 for (dataWeight in it.data!!){
     ageEntry = dataWeight.date.toLocalDate().getAgeInMonth().toString().toInt()
     dataObject.plusElement(arrayOf(ageEntry.toDouble(), dataWeight.weight.toDouble()))
     Log.d("DATA_SERIES_BARU", "setupViewInstance: ${dataObject.contentToString()}")
 }

Log

enter image description here

CodePudding user response:

The OP's proposed answer is subpar to say the least. If you need a mutable data structure, use a list not an array. I suggest something along those lines:

it.data?.fold(ArrayList<Array<Double>>()) { list, dataWeight ->
    val ageEntry = dataWeight.date.toLocalDate().getAgeInMonth().toString().toInt()
    list.add(arrayOf(ageEntry.toDouble(), dataWeight.weight.toDouble()))
    list
}

If you absolutely need an array at the end, you can easily convert it using toTypedArray().

CodePudding user response:

Im adding this function to add array Element

fun <T> appendArray(arr: Array<T>, element: T): Array<T?> {
        val array = arr.copyOf(arr.size   1)
        array[arr.size] = element
        return array
    }

then you can call it

appendArray(copyDataObject, arrayOf(ageEntry,arrayOf(arrayOf(2.0, 3.0)))
  • Related