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 setName = setOf(val1, val2, val3) 

Note: Similar 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 referenced 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 Techonologies.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

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?