A 'Set' is a Collection that can also hold multiple values. And a 'Set' is unordered and doesn't allow duplicate values.
The declaration of a 'Set' 'Data Type' is super easy. You can place multiple values inside the method 'setOf()' or 'mutableSetOf()' and Kotlin will understand that it is a 'Set'.
Using the 'setOf()' method, we can create an immutable set(i.e. A read only Set).
fun main() { var x = setOf(5, "John", "Kotlin") println(x) }
So, in the above code we have created a 'Set' using the 'setOf()' method.
And put an Integer type value (i.e. 5) and two String type value (i.e. 'John' and 'Kotlin')
And initialised to the variable 'x'.
So, we can see that two different data types are assigned to a 'Set'.
In the next line we have printed the 'Set' using the print statement.
Now, if we see the output,
The values are enclosed inside square brackets '[]'. This means that the values are inside a Set.
fun main() { var x = setOf(5, "John", "Kotlin", "John") println(x) }
So, in the above code we have created a 'Set' using the values, 5, "John", "Kotlin" and "John".
Now, if we see the output,
You can see only three values are printed.
This is because in the above Set, the name 'John' is present twice.
And since a Set doesn't accept duplicates, the name 'John' is not inserted to the set twice.
And we see the above output with 'John' present only once.
So, in the above code we have created a Set with 2 different Datatype(i.e. String and Integer).
Now, what if we want to restrict the Set to accept only a String or an Integer or a Float.
Let's see in the below example.
fun main() { var x: Set<String> = setOf(5, "John", "Kotlin") println(x) }
So, what we have done is, created a Set with three values, '5', 'John' and 'Kotlin'.
And at the time of initialisation, we have ended up with an error.
This is because we have restricted the Set to accept only values of String datatype.
And the values we are trying to use contains an integer value i.e. '5'.
Now, let us try inserting all String values.
fun main() { var x: Set<String> = setOf("Tom", "John", "Kotlin") println(x) }
Now, if you look at the output. We got the correct entries printed.
Using the 'mutableSetOf()' method, we can create a mutable set(i.e. The Set values can be changed/replaced).
fun main() { var x = mutableSetOf(5, "John", "Kotlin") println(x) }
So, the values are enclosed inside square brackets '[]'. This means that the values are inside a Set.
Now, what if we don't want the output enclosed in square brackets '[]'.
Let us check that in the next tutorial.