Kotlin List Interface
Kotlin List is an interface and generic collection of elements. The List interface inherits form Collection<T> class. It is immutable and its methods supports only read functionalities.
To use the List interface we need to use its function called listOf(), listOf<E>().
The elements of list follow the sequence of insertion order and contains index number same as array.
List Interface Declaration
Function of Kotlin List Interface
There are several functions are available in the List interface. Some functions of List interface are mention below.
Functions | Descriptions |
---|---|
abstract fun contains(element: E): Boolean | It checks specified element is contained in this collection. |
abstract fun containsAll(elements: Collection<E>): Boolean | It checks all elements specified are contained in this collection. |
abstract operator fun get(index: Int): E | It returns the element at given index from the list. |
abstract fun indexOf(element: E): Int | Returns the index of first occurrence of specified element in the list, or -1 if specified element is not present in list. |
abstract fun isEmpty(): Boolean | It returns the true if list is empty, otherwise false. |
abstract fun iterator(): Iterator<E> | It returns an iterator over the elements of this list. |
abstract fun lastIndexOf(element: E): Int | It returns the index of last occurrence of specified element in the list, or return -1 if specified element is not present in list. |
abstract fun listIterator(): ListIterator<E> | It returns a list iterator over the elements in proper sequence in current list. |
abstract fun listIterator(index: Int): ListIterator<E> | It returns a list iterator over the elements in proper sequence in current list, starting at specified index. |
abstract fun subList(fromIndex: Int, toIndex: Int): List | It returns a part of list between fromIndex (inclusive) to toIndex (exclusive). |
Kotlin List Example 1
Let’s see an example of list using listOf() function.
Output:
Ajay Vijay Prakash
Kotlin List Example 2
In the listOf() function we can pass the different types of data at the same time. List can also traverse the list using index range.
Output:
1 2 3 Ajay Vijay Prakash 1 2 3 Ajay Vijay Prakash
Kotlin List Example 3
For more specific we can provide the generic types of list such as listOf<Int>(), listOf<String>(), listOf<Any>() Let’s see the example.
Output:
print int list 1 2 3 print string list Ajay Vijay Prakash print any list 1 2 3 Ajay Vijay Prakash
Kotlin List Example 4
Let’s see the use of different function of Kotlin list interface using listOf<T>() function.
Output:
Ajay Vijay Prakash Vijay Rohan Ajay 1 3 5 true true [Prakash, Vijay] false [Vijay, Prakash, Vijay, Rohan] [Ajay, Vijay, Prakash]
The limitation of List interface is that it is immutable. It cannot add more elements in list after its declaration. To solve this limitation Collection framework provide mutable list.