In this tutorial, you shall learn how to get the size of a given Set in Kotlin using Set.size property, with examples.

Kotlin Set Size

To get the size of a Set in Kotlin, we can read the size property of this Set. size property returns an integer representing the number of elements in this Set.

The syntax to read size property on given Set mySet is

mySet.size

To read size property on a Set, the Set must be initialized.

Examples

ADVERTISEMENT

1. Get the size of give set object

In the following program, we will take a Set with some values, and find its size using Set.size property.

Main.kt

fun main(args: Array<String>) {
    var mySet = setOf(1, 4, 9, 16, 25)
    val len = mySet.size
    println("The size of given Set is : ${len}")
}

Output

The size of given Set is : 5

2. Get the size of a set that is not initialized

If the Set is not initialized, then the build fails with the error: Kotlin: Variable ‘mySet’ must be initialized.

In the following example, we have declared a Set of Integers, but not initialized it. Let us try to read the size property of this Set.

Main.kt

fun main(args: Array<String>) {
    var mySet : Set<Int>
    val len = mySet.size
    println("The size of given Set is : ${len}")
}

Output

/Users/tutorialkart/IdeaProjects/KotlinTutorial/src/Main.kt:3:15
Kotlin: Variable 'mySet' must be initialized

Conclusion

In this Kotlin Tutorial, we learned how to get the size of a Set, with the help of examples.