如何在Kotlin中添加项目到列表

Moh*_*pal 6 kotlin kotlin-android-extensions

我正在尝试将元素列表添加到字符串列表中,但是我发现Kotlin没有像java这样的添加功能,因此请帮助我如何将项目添加到列表中。

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

            }
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

kco*_*ock 45

更惯用的方法是使用MutableList而不是专门使用ArrayList. 您可以声明:

val listOfVehicleNames: MutableList<String> = mutableListOf()
Run Code Online (Sandbox Code Playgroud)

并以这种方式添加它。或者,您可能希望更喜欢不变性,并将其声明为:

var listOfVehicleNames: List<String> = emptyList()
Run Code Online (Sandbox Code Playgroud)

在您的完成块中,只需重新分配它:

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

  • 哦,是的,这太明显了!比java简单多了。我很高兴我们换了。 (13认同)

Rad*_*esh 41

如果您不想或不能直接使用数组列表,请使用此代码添加项目

itemsList.toMutableList().add(item)
Run Code Online (Sandbox Code Playgroud)

itemlist : 你的物品清单

item : 要添加的项目

  • 你没有错过任务吗?toMutableList() 创建 itemsList 的副本并且不会更改它,对吗? (2认同)
  • 我认为你是对的,缺少一个赋值,而且 .add(item) 返回一个布尔值,所以如果我没有记错的话,这必须分多个步骤完成。 (2认同)
  • 它不会改变 itemsList 的任何内容 (2认同)

Jon*_*nik 33

谈论一种惯用的方法......

当您只能使用不可变列表(通常在 Kotlin 中)时,只需使用+plus。它返回一个新列表,其中包含原始列表的所有元素加上新添加的元素:

val original = listOf("orange", "apple")
val modified = original + "lemon" // [orange, apple, lemon]
Run Code Online (Sandbox Code Playgroud)

original.plus("lemon")产生与 相同的结果original + "lemon"。稍微冗长一些,但在组合多个集合操作时可能会派上用场:

return getFruit()
       .plus("lemon")
       .distinct()
Run Code Online (Sandbox Code Playgroud)

除了添加单个元素之外,您还可以使用plus连接整个集合:

val original = listOf("orange", "apple")
val other = listOf("banana", "strawberry")
val newList = original + other // [orange, apple, banana, strawberry]
Run Code Online (Sandbox Code Playgroud)

免责声明:这并没有直接回答 OP 的问题,但我觉得在题为“如何在 Kotlin 中将项目添加到列表中?”的问题中,plus 必须提及该主题的 Google 热门话题。


Bre*_*ent 9

而不是使用不可变的常规列表,只需使用可变的 arrayListof

所以你的常规列表将变成

var listofVehicleNames = arrayListOf("list items here")
Run Code Online (Sandbox Code Playgroud)

然后你可以使用添加功能

listOfVehicleNames.add("what you want to add")
Run Code Online (Sandbox Code Playgroud)


小智 6

你应该使用像 ArrayList 这样的 MutableList

var listofVechileName:List<String>?=null
Run Code Online (Sandbox Code Playgroud)

变成

 var listofVechileName:ArrayList<String>?=null
Run Code Online (Sandbox Code Playgroud)

并且你可以使用方法添加

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