Kotlin Set - Size Property



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

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

Syntax

Following is the syntax of Kotlin set size property −

Set.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 set.

Example 1: If Set is not Empty

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

fun main(args: Array<String>) {
   val set = setOf(1, 2, 3, 4, 5)
   val totalElement = set.size
   println("Total number of elements: $totalElement")
}

Output

Following is the output −

Total number of elements: 5

Example 2: Set with Duplicate Element

The following example gives the total number of elements in the current set and will only display distinct elements −

fun main(args: Array<String>) {
   val set = setOf(1, 2, 3, 4, 4, 1, 5)
   val totalElement = set.size
   println("Total number of elements: $totalElement")
   println("Distinct Element: " + set)
}

Output

Following is the output −

Total number of elements: 5
Distinct Element: [1, 2, 3, 4, 5]

Example 3: If Set is Empty

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

fun main(args: Array<String>) {
   val set = setOf<String>()
   val totalElement = set.size
   println("Total number of elements: $totalElement")
   println("Set's Element: " + set)
}

Output

Following is the output −

Total number of elements: 0
Set's Element: []
kotlin_sets.htm
Advertisements