
So I don't actually need to say too much more about them. But generally you can think of a list in Kotlin, you can work with it in pretty much the same way as you would do in Java. We can look through them, and we're going to talk a bit more about special things we can do with the lists when we get to the chapter on functional programming. Now, the way we work with lists in Kotlin, we've already seen a little bit. That will create for us an empty, mutable list, but we can supply integers into that list. In other words, if we had a mutable list of numbers and I didn't want to provide any initial values, we'd say mutable list of, but I'd put in here in angle brackets int, for example, and leave my brackets empty. Isolating a mutable state to a single thread, and allowing other threads to communicate with that state, is an alternative method for achieving concurrent mutability. Atomics allow mutability from any thread. When we use mutable list of, we don't have to provide initial values, but if we don't, then we must provide the data type in the form of a generic class. Rule 1 of Kotlin/Native state is that a mutable state is visible to only one thread. Well, let's go for Monday, Tuesday, and Wednesday. Therefore, it’s not possible to detect whether a list is a MutableList at runtime. Compile-time references to List and MutableList are both compiled to references. Well, rather than using list of, we can say mutable list of and provide the values. At runtime, Kotlin uses Java collection classes, which only have a single List interface containing both read and mutation methods. Let's create a list called days, and I want this one to be a mutable list. If we want to create a mutable list, well, we can do that, as we've already seen, by creating a new array list, but there's also a more Kotlin-like syntax that we can use.
Common 1.0 class ArrayListI prefer to add my own extension to be sure of the result and create a much more clear code (just like we have for arrays): fun List.- So that's an immutable list. Provides a MutableListimplementation, which uses a resizable array as its backing storage. For instance, adding the following line at the beginning of the extension: if (this is List) return this is a legitimate performance improvement (if it indeed improves the performance).Īlso, because of its name, the resulting code isn't very clear.

Nothing guarantees you that it's going to be a new list.

Unfortunately, as its signature and documentation suggest, it's meant to ensure that an Iterable is a List (just like toString and many other to methods). method takes an iterable such as a list of integers between 0 and 256.

You can use the provided extension Iterable.toMutableList() which will provide you with a new list. It provides developers the usual methods Python affords to both mutable and byte.
