androidlistkotlinmutablelist

Getting only last element from the list [Kotlin]


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


Solution

  • 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")
    }