As previously discussed, Kotlin collections fall under two categories: mutable and immutable, and sets are no exception. An immutable set is declared using the setOf keyword and indicates a set whose values cannot change throughout a program:

var/val setName = setOf(val1, val2, val3) 

Note: Similarly to lists, the set type can be inferred by the compiler or declared in the code. For example, a set comprised of String values would be inferred as a Set<String>.

In the code below, we are creating a new set and storing it in the variable, colorsOftheRainbow:

var colorsOfTheRainbow = setOf("red", "orange", "yellow", "green", "blue", "red")

Logging colorsOfTheRainbow to the console, notice that there is one less color in the set. The last element, "red", was a duplicate String that the set object recognized and removed:

println(colorsOfTheRainbow) // Prints: [red, orange, yellow, green, blue]




In Technologies.kt, declare a variable, obsoleteTech, and assign it an immutable set with the following values:

  • "Rolodex"
  • "Phonograph"
  • "Videocassette recorder"
  • "Video projector"
  • "Rolodex"

Output the value of the set using a print statement. Notice how there’s one less item in the final set.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?