With immutable sets, we don’t have much control over the contents they store, but with mutable sets, we are able to add, remove, or replace as many elements as we’d like. This allows us to work both with sets that are populated with values and empty sets, which are sets that are initialized without any values but can be populated at a later time.

To initialize an empty mutable set, we’d use the following syntax:

var/val setName = mutableSetOf<Type>()
  • The term, mutableSetOf is used to declare a mutable set.
  • The term is followed by the type of data that we expect the set to hold and a pair of empty parentheses.

Assume we’re developing a program for a building manager who would like to keep track of the apartments they own. Unfortunately, we haven’t received the apartment information from them just yet, so we create a mutable set and wait until we can populate it with values:

var totalApts = mutableSetOf<String>()

While we wait, let’s practice declaring a set that comes prepopulated with values. The syntax is as follows:

var/val setName = mutableSetOf(value1, value2, value3)

No need to specify the set type here as it will automatically be inferred by the compiler. Let’s see an example:

var nycRadioStations = mutableSetOf(106.7, 101.1, 97.1, 103.5)

The compiler will infer mutableSetOf<Double> from the code above and will only accept values of type Double within this set going forward.



In Moon.kt, create a mutable set, apolloLandingSites, populated with the following String values:

  • "Mare Tranquillitatis"
  • "Fra Mauro"
  • "Hadley/Apennines"
  • "Descartes"
  • "Taurus-Littrow"
  • "Oceanus Procellarum"

These values represent the 6 Apollo Moon landing sites. 🌕


Output the values of the set using a print statement. Think about what type of Kotlin program can be written with this data.

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?