Brijesh Joshi
Brijesh Joshi

Reputation: 1857

How does add method works for List<E> type val in kotlin

I'm having a variable like

val itemList:List<String> = ArrayList()
itemList.add("One")
itemList.add("Two")

How can i achieve this in kotlin

Upvotes: 3

Views: 6632

Answers (3)

EpicPandaForce
EpicPandaForce

Reputation: 81539

A few options:

val itemList: List<String> = arrayListOf<String>().apply {
    add("One")
    add("Two")
}
// no need for .add method anymore!

Another option:

val itemList: MutableList<String> = mutableListOf()
// or
val itemList = mutableListOf<String>()

// now you have `.add()` function

You should generally prefer non-modifiable lists instead of modifiable lists. For example, in Java, you could only use Collections.unmodifiableList and get a runtime exception if you tried to make a modification. With Kotlin, you can make it into a compile-time validation.

Upvotes: 1

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75788

Don't

val itemList:List<String> = ArrayList()

Do

 val itemList:MutableList<String> = ArrayList()

You should use MutableList.

interface MutableList<E> : List<E>, MutableCollection<E> (source)

A generic ordered collection of elements that supports adding and removing elements.

DEMO

 val itemList:MutableList<String> = ArrayList()
    itemList.add("One")
    itemList.add("Two")

Upvotes: 12

user4571931
user4571931

Reputation:

Try this code..

class UserActivity : AppCompatActivity() {
val itemList= ArrayList<String>()
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    itemList.add("One")
    itemList.add("Two")
}

}

Upvotes: 0

Related Questions