Home > OS >  Getting only last element from the list [Kotlin]
Getting only last element from the list [Kotlin]

Time:07-30

This problem is in reference to Android : I have a function which takes in a string value and I want to print a list of Integers from 0 upto that number. I am able to get the string inside the loop but outside the loop I am only getting the last element.

What am I missing here? Any help would be appreciated.

My code :

private fun floorsListFromReceived(floors: String): MutableList<Int> {

        var floorList: MutableList<Int> = mutableListOf()
        var count = 0
        while( count <= floors.toInt()) {
            floorList = mutableListOf(count)
            count  
            Timber.d("List of Floors Inside is : $floorList")
        }
        Timber.d("List of Floors Outside  is : $floorList")
        return floorList
    }

LOG : enter image description here

CodePudding user response:

Yes I am trying to make a list so therefore floorList = mutableListOf(count) so after every loop count gets added to the list.

Then you should do like this:

while (count <= floors.toInt()) {
    floorList.add(count)
    count  
    Timber.d("List of Floors Inside is : $floorList")
}

CodePudding user response:

You are recreating the list every time you go through the while loop floorList = mutableListOf(count). You need to just use the mutableList you already created before, floorList and add your values to it using the add function.

Also, you can use a for loop instead of a while loop for better readability.

var floorList: MutableList<Int> = mutableListOf()
for (count in 0 .. floors.toInt()){
    floorList.add(count)
}

Or an even easier aproach with a list comprehension like aproach like this.

val floorsList =(0 .. floors).toList()

or this

val floorsList = List(floors.toInt()) { it }
  • Related