The size property of the Set class in Kotlin returns the number of elements in the set.
The syntax of Set.size property is:
abstract val size: Int
This size property of Set returns the number of elements in the set.
Set.size returns value of type Int
.
In Kotlin, we can use the size
property to get the number of elements in a set.
For example,
size
property to get the number of elements in the set.println
function.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")
}
The size of the set is: 5
In Kotlin, we can check if a set is empty by comparing the size
property to zero.
For example,
println
function.fun main(args: Array<String>) {
val emptySet = emptySet<String>()
val isEmpty = emptySet.size == 0
println("Is the set empty? $isEmpty")
}
Is the set empty? true
In Kotlin, the size
property can also be used with mutable sets to get the number of elements.
For example,
size
property to get the number of elements in the set.println
function.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")
}
The size of the mutable set is: 4
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.