To create an empty set in Kotlin, you can use the emptySet
function or the setOf
function with no arguments.
In this example,
emptySet
function which is a standard library function in Kotlin that returns an empty read-only set.set1
and assign it the result of the emptySet
function.emptySet
function is generic and infers the type of the set based on the context. If no context is provided, it will create a set of type Nothing
.set1
to standard output to verify its contents.fun main(args: Array<String>) {
val set1 = emptySet<String>()
println("Contents of set1: $set1")
}
Contents of set1: []
In this example,
setOf
function which is a standard library function in Kotlin that can be used to create a read-only set.set2
and assign it the result of the setOf
function with no arguments.setOf
function is also generic and infers the type of the set based on the context. Here, we explicitly specify the type String
to ensure the set is of type Set
.set2
to standard output to verify its contents.fun main(args: Array<String>) {
val set2 = setOf<String>()
println("Contents of set2: $set2")
}
Contents of set2: []
In this tutorial, we learned How to create an Empty Set in Kotlin language with well detailed examples.