Kotlin List Interface

Before we jump onto List in Kotlin. Let’s just have a look at what java has to offer us in terms of the list. Java List helps us to maintain the ordered collection.

It has the index-based methods to insert, update, delete, and search all the elements in a list. In the java list, we can also store the null elements. The List Interface is found in the java.util package and inherits the collection interface. We can iterate the list in the forward or backward directions.

Java List Declaration:

public interface List<E> extends Collection<E>

A sample Java Code for the List:

import java.util.*;  

public class ListExample1{  
public static void main(String args[]){  
 //Creating a List  
 List<String> list=new ArrayList<String>();  

 //Adding elements in the List  
 list.add("Ishank");  
 list.add("Aditya");  
 list.add("Yugansh");  
 list.add("Deepansh");  

 //Iterating the List element using for-each loop  
 for(String name:list)  
  System.out.println(name);  
 
}
}

The output for the following code is:

Ishank
Aditya
Yugansh
Deepansh

Kotlin List Interface

Kotlin List is basically an interface and the generic collection of elements. List interface is inherited from the Collection<T> class. Kotlin list is immutable and their methods support only the read functionalities.

If we want to use the List Interface in the Kotlin, we need to use its function named as listof( ), listof<E>( ).

All the elements of the List always follow the sequence of the insertion order and contain the index number which is the same as the array.

List Interface Declaration:

In Kotlin we declare the List as follows:

public interface List<out E> : Collection<E> (source)

Now let just see how we can make a List in Kotlin Language.

Kotlin List Example 1:

fun main(args: Array<String>){  
    var list = listOf("Ishank","Yugansh","Deepansh")
    for(element in list){  
        println(element) }
}

The output will be as follows:

Ishank
Yugansh
Deepansh

Kotlin List Example 2:

listof() function we can also pass the different types of data at the same time. Lists can also traverse using the index range.

fun main(args: Array<String>){  
    var list = listOf(1,2,3,"Ishank","Yugansh","Deepansh")//read only, fix-size  
    for(element in list){  
        println(element)  
    }  
    println()  
    for(index in 0..list.size-1){  
        println(list[index])  
    }  
}

The output will be as follows:
1
2
3
Ishank
Yugansh
Deepansh

1
2
3
Ishank
Yugansh
Deepansh

Comment down below if you have any queries related to list in kotlin.

Leave a Comment

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!