103

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

            }
        })
    }
}
5
  • huh? what list are you talking about? Kotlin lists ARE Java lists, aren't they? I'm sorry if the foreign names are throwing me off.
    – CryptoFool
    Apr 3, 2019 at 6:25
  • @Steve I'm talking about var listofVechileName:List<String>?=null how to add the item on it Apr 3, 2019 at 6:27
  • 2
    You need to take a step back, and read the documentation to learn the fundamentals of Kotlin, by simply reading the documentation: kotlinlang.org/docs/reference/collections.html
    – JB Nizet
    Apr 3, 2019 at 6:32
  • Ah yes...the immutable thing. I just didn't put 2 and 2 together on this one. Makes perfect, obvious sense. I don't get to do enough Kotlin coding yet. It's not about reading the docs. Rather, it's about doing your day job in Java, and having to pull your head out of that and think in Kotlin.
    – CryptoFool
    Apr 3, 2019 at 6:47
  • 1
    A simple answer, you can't directly add items to List without converting it to its mutable form.
    – iCantC
    Feb 4, 2020 at 7:08

8 Answers 8

75

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.

2
  • The one thing with .plus() is that it has to be a MutableList. Regular List doesn't implement that. May 6, 2022 at 21:35
  • 1
    @JayWhitsitt That is incorrect. Please try running the code examples in my answer. For example listOf returns a read-only list, yet you absolutely can call plus() on that. As I mentioned above, plus returns a new list; it never modifies the original list.
    – Jonik
    May 17, 2022 at 20:05
74

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 */ }
0
53

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

4
  • 2
    Didn't you miss an assignment? toMutableList() creates a copy of itemsList and doesn't change it, right? Jul 20, 2021 at 9:21
  • 2
    I think you're correct, an assignment is missing and also, .add(item) returns a Boolean so this has to be done in multiple steps, if I'm not mistaken.
    – jure
    Nov 26, 2021 at 13:26
  • 1
    @PhilipRego don't use it in initialize. use it like this => aggList.toMutableList().add(user) , in initialize => var aggList: List<User> = emptyList<User>
    – Radesh
    Jul 6, 2022 at 6:49
  • 2
    It doesn't change anything about itemsList
    – c-an
    Sep 12, 2022 at 4:02
11

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")
8

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

1
  • I didnt want to change too much author, but as someone makes me notice you should avoid to init to null, it would be better using lazeinit
    – Peppe Scab
    Apr 3, 2019 at 12:45
4

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

            }
        }
2

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

0
var list = listOf("a")
list += "b"
3
  • Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation? Nov 22 at 19:44
  • @JeremyCaney no other answer here uses += (exept a deleted one). other answers use foo = foo + item, but not +=.
    – starball
    Nov 23 at 1:15
  • @starball: The contributor should still explain why this is preferable over existing approaches. That will make this answer far more useful, and especially to readers new to the syntax. Nov 24 at 6:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.