Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {

            }
        })
    }
}
like image 493
Mohit Lakhanpal Avatar asked Apr 03 '19 06:04

Mohit Lakhanpal


People also ask

How do I add items to my Kotlin list?

To add a single element to a list or a set, use the add() function. The specified object is appended to the end of the collection. addAll() adds every element of the argument object to a list or a set.

How do I add an item to an ArrayList in Kotlin?

We can insert an item to an ArrayList using the add() function provided by the Kotlin library. In this example, we will be creating two lists: one is "myMutableList" which is a collection of mutable data types, and the other one is "myImmutableList" which is a collection of immutable data types.

How do I add items to my list on first position Kotlin?

Using add() function The standard solution to prepend an element to the front of a list, you can use the add() function with the specified index as 0. You can easily extend the solution to add multiple elements to the front of the list.


2 Answers

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 */ }
like image 191
Kevin Coppock Avatar answered Oct 13 '22 02:10

Kevin Coppock


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.

like image 55
Jonik Avatar answered Oct 13 '22 04:10

Jonik