Kotlin Set size
Syntax & Examples
Set.size property
The size property of the Set class in Kotlin returns the number of elements in the set.
Syntax of Set.size
The syntax of Set.size property is:
abstract val size: Int
This size property of Set returns the number of elements in the set.
Return Type
Set.size returns value of type Int
.
✐ Examples
1 Getting the size of a set
In Kotlin, we can use the size
property to get the number of elements in a set.
For example,
- Create a set of integers.
- Use the
size
property to get the number of elements in the set. - Print the size to the console using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5)
val size = numbers.size
println("The size of the set is: $size")
}
Output
The size of the set is: 5
2 Checking if a set is empty using size
In Kotlin, we can check if a set is empty by comparing the size
property to zero.
For example,
- Create an empty set of strings.
- Check if the size of the set is zero to determine if it is empty.
- Print the result to the console using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val emptySet = emptySet<String>()
val isEmpty = emptySet.size == 0
println("Is the set empty? $isEmpty")
}
Output
Is the set empty? true
3 Using size property with mutable set
In Kotlin, the size
property can also be used with mutable sets to get the number of elements.
For example,
- Create a mutable set of strings.
- Add elements to the set.
- Use the
size
property to get the number of elements in the set. - Print the size to the console using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val mutableSet = mutableSetOf("apple", "banana", "cherry")
mutableSet.add("date")
val size = mutableSet.size
println("The size of the mutable set is: $size")
}
Output
The size of the mutable set is: 4
Summary
In this Kotlin tutorial, we learned about size property of Set: the syntax and few working examples with output and detailed explanation for each example.