Kotlin List - Size Property



The Kotlin List size property is an attribute of the collection interface, used to return the number of elements available in the list.

We can access the size property directly without calling the function.

Syntax

Following is the syntax of Kotlin list size property −

List.size

Parameters

size is a property so it does not accepts any parameters.

Return value

The size property returns the integer value that represents the length of the list.

Example 1: If List is not Empty

Let's see a basic example of the size property, which returns number of elements in the list.

fun main(args: Array<String>) {
   val list = listOf<String>("tutorialspoint", "aman", "kumar");
   val total_element = list.size;
   println("The size of element: " + total_element)
}

Output

Following is the output −

The size of element: 3

Example 2: List with Different Types of Element

The following example gives the total number of elements in the current list −

fun main(args: Array<String>) {
   val list = listOf<Any>(1, 2, 'a', 'B', "tutorialspoint", "aman");
   val total_element = list.size;
   println("Total number of elements: " + total_element)
}

Output

Following is the output −

Total number of elements: 6

Example 3: If List is Empty

This is another example of size property. If the list is empty, it returns 0 −

fun main(args: Array<String>) {
   val list = listOf<Any>()
   val totalElement = list.size
   println("Total number of elements: $totalElement")
}

Output

Following is the output −

Total number of elements: 0
kotlin_lists.htm
Advertisements