To initialize a set in Kotlin, you can use the setOf
function or the mutableSetOf
function for immutable and mutable sets, respectively.
In this example,
setOf
function, which is a standard library function in Kotlin that creates a read-only (immutable) set.set1
and assign it the result of calling the setOf
function with several string arguments, such as "apple"
, "banana"
, and "cherry"
.setOf
function creates an immutable set containing the specified elements.set1
to the standard output to verify its contents. Immutable sets do not allow modification, so we will not attempt to add or remove elements from it.fun main() {
val set1 = setOf("apple", "banana", "cherry")
println("Contents of set1: $set1")
}
Contents of set1: [apple, banana, cherry]
In this example,
mutableSetOf
function, which is a standard library function in Kotlin that creates a mutable set.set2
and assign it the result of calling the mutableSetOf
function with several string arguments, such as "apple"
, "banana"
, and "cherry"
.mutableSetOf
function creates a mutable set containing the specified elements.set2
using the add
method, passing "date"
as the argument.set2
using the remove
method, passing "banana"
as the argument.set2
to the standard output to verify its contents, demonstrating that the set can be modified.fun main() {
val set2 = mutableSetOf("apple", "banana", "cherry")
set2.add("date")
set2.remove("banana")
println("Contents of set2: $set2")
}
Contents of set2: [apple, cherry, date]
In this tutorial, we learned How to Initialize a Set in Kotlin language with well detailed examples.