Unlike Java, Kotlin has two different interfaces for working with collections. The plain collection interface which handles accessing data and the MutableCollection interface that handles modifying the data. In this video, get an overview of both types.
- [Instructor] Unlike Java, Kotlin has two different interfaces for working with collections. The plain Collection interface handles accessing data and then the MutableCollection interface handles modifying the data. As you can see here, this interface lets you check the size and contents of the Collection as well as iterate over its items, whereas the MutableCollection interface extends it with the additional ability to add, remove, and clear the contents of the collection. Just to illustrate, if we created an array list of integers and declared the variable type to be collection events, then we would receive an unresolved reference error when attempting to invoke the add method.
Now this is because the Kotin Collection interface does not contain that particular method, but if we change the return type to be a MutableCollection, then we're good to go and we can add elements to our list of numbers. This type of separation is useful for reducing bugs in your code and making your intent clear. When it comes to collections in Kotlin, they are either read-only or mutable. And since Kotlin uses Java collections under the HUD, it's still interoperable with Java.
The compiler just maps the Java collection to the appropriate Kotlin interface. Now when you want to create collections of different types, you have a few options available to you. For example, if you want to create a list, but you want that list to be read-only, then you would use the listOf function to create it, but if you want it to be able to modify your list, then you would use the mutableListOf function in the structures similar for other collection types like map and set. But you're not limited to only those methods that start with the word mutable.
There are other methods, like this one for maps, sortedMapOf. This returns a mutable map. This allows us to add items to our map, and when printed out, we can see them sorted. The best way I found to discover possible functions is by using the IDE and seeing what suggestions it provides when I type something like mapOf. So you should try it out so you can see what other functions are available.
- What Kotlin has to offer
- Working with lambdas
- Common Android extension functions
- Kotlin Android Extensions overview
- Making use of the Anko library
- Working with coroutines
- Nullability and collections