Mohit Lakhanpal
Mohit Lakhanpal

Reputation: 1495

How to add an item to a list in Kotlin?

I'm trying to add an element list to the list of string, but I found Kotlin does not have an add function like java so please help me out how to add the items to the list.

class RetrofitKotlin : AppCompatActivity() {

    var listofVechile:List<Message>?=null
    var listofVechileName:List<String>?=null
    var listview:ListView?=null
    var progressBar:ProgressBar?=null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_retrofit_kotlin)

        listview=findViewById<ListView>(R.id.mlist)
        var apiInterfacee=ApiClass.client.create(ApiInterfacee::class.java)
        val call=apiInterfacee.getTaxiType()
        call.enqueue(object : Callback<TaxiTypeResponse> {

            override fun onResponse(call: Call<TaxiTypeResponse>, response: Response<TaxiTypeResponse>) {

                listofVechile=response.body()?.message!!
                println("Sixze is here listofVechile   ${listofVechile!!.size}")
                if (listofVechile!=null) {
                    for (i in 0..listofVechile!!.size-1) {

                        //how to add the name only listofVechileName list

                    }
                }
                //println("Sixze is here ${listofVechileName!!.size}")
                val arrayadapter=ArrayAdapter<String>(this@RetrofitKotlin,android.R.layout.simple_expandable_list_item_1,listofVechileName)
                listview!!.adapter=arrayadapter

            }
            override fun onFailure(call: Call<TaxiTypeResponse>, t: Throwable) {

            }
        })
    }
}

Upvotes: 113

Views: 248638

Answers (8)

M. Marmor
M. Marmor

Reputation: 440

var list = listOf("a")
list += "b"

Upvotes: 2

Antriksh Chhipa
Antriksh Chhipa

Reputation: 31

val listofVechile = mutableListOf<String>()

Declare mutable list like that and you will be able to add elements to list :

listofVechile.add("car")

https://kotlinlang.org/docs/collections-overview.html

Upvotes: 3

Vinod Joshi
Vinod Joshi

Reputation: 7862

For any specific class, the following may help

 var newSearchData = List<FIRListValuesFromServer>()

        for (i in 0 until this.singleton.firListFromServer.size) {

            if (searchText.equals(this.singleton.firListFromServer.get(i).FIR_SRNO)) {

                newSearchData.toMutableList().add(this.singleton.firListFromServer.get(i))

            }
        }

Upvotes: 4

Brent
Brent

Reputation: 778

instead of using a regular list which is immutable just use an arrayListof which is mutable

so your regular list will become

var listofVehicleNames = arrayListOf("list items here")

then you can use the add function

listOfVehicleNames.add("what you want to add")

Upvotes: 12

Jonik
Jonik

Reputation: 81751

Talking about an idiomatic approach... 🙄

When you can get away with only using immutable lists (which means usually in Kotlin), simply use + or plus. It returns a new list with all elements of the original list plus the newly added one:

val original = listOf("orange", "apple")
val modified = original + "lemon" // [orange, apple, lemon]

original.plus("lemon") yields the same result as original + "lemon". Slightly more verbose but might come in handy when combining several collection operations:

return getFruit()
       .plus("lemon")
       .distinct()

Besides adding a single element, you can use plus to concatenate a whole collection too:

val original = listOf("orange", "apple")
val other = listOf("banana", "strawberry")
val newList = original + other // [orange, apple, banana, strawberry]

Disclaimer: this doesn't directly answer OP's question, but I feel that in a question titled "How to add an item to a list in Kotlin?", which is a top Google hit for this topic, plus must be mentioned.

Upvotes: 87

Radesh
Radesh

Reputation: 13565

If you don't want or can't use array list directly use this code for add item

itemsList.toMutableList().add(item)

itemlist : list of your items

item : item you want to add

Upvotes: 54

Kevin Coppock
Kevin Coppock

Reputation: 134664

A more idiomatic approach would be to use MutableList instead of specifically ArrayList. You can declare:

val listOfVehicleNames: MutableList<String> = mutableListOf()

And add to it that way. Alternatively, you may wish to prefer immutability, and declare it as:

var listOfVehicleNames: List<String> = emptyList()

And in your completion block, simply reassign it:

listOfVehicleNames = response.body()?.message()?.orEmpty()
    .map { it.name() /* assumes name() function exists */ }

Upvotes: 75

Peppe Scab
Peppe Scab

Reputation: 150

you should use a MutableList like ArrayList

var listofVechileName:List<String>?=null

becomes

 var listofVechileName:ArrayList<String>?=null

and with that you can use the method add

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-list/add.html

Upvotes: 8

Related Questions