Topic Overview and Actualization

In today's lesson, we're going to dive into an important Kotlin data structure: Sets. A Set, just as it is in mathematics, is a collection of distinct elements, meaning it cannot contain duplicate values. They are useful in many scenarios, such as when you want to keep a record of unique items. For instance, imagine you have a list of books in a library, and you want to know the available different genres without going through the same genre multiple times. A Set would be the preferred data structure for such a case.

In this lesson, we'll learn how to create Sets, manage their elements, and utilize their properties. Combined with what we've already learned about Arrays and Lists, this knowledge will empower you with a strong understanding of Kotlin data structures.

Introduction to Sets in Kotlin

Sets are one of the data structures provided by Kotlin for storing different types of data, akin to Arrays and Lists. However, in contrast to Arrays and Lists, Sets hold unique elements, meaning no two elements in a Set can be identical. This uniqueness property of a Set makes it ideal for use when you want to avoid storing duplicate data.

Imagine you're running a unique email drawing competition where everyone with an email is allowed to participate once. A Kotlin Set would be the perfect container for the emails because it would ensure each email is listed only once.

Having said that, you must remember that a Set will not keep track of the order in which elements were inserted. So always remember this when dealing with Sets: the order doesn't matter, and each element is unique!

Creating and Managing Sets in Kotlin

Creating Sets in Kotlin is a breeze. Kotlin offers us the setOf() function to create an immutable Set and the mutableSetOf() function to create a mutable Set. Immutable sets cannot be modified after creation, while mutable sets allow changes. Here's how you can create sets:

Kotlin
fun main() {
  // Creating an immutable Set
  val numbers = setOf("one", "two", "three") // This set cannot be modified
  println("Immutable set: $numbers") // Prints "Immutable set: [one, two, three]"

  // Creating a mutable Set
  val mutableNumbers = mutableSetOf("one", "two", "three")

  // Changing mutable Set
  mutableNumbers.add("four") // Adds "four" into mutableNumbers
  mutableNumbers.add("four") // Adds "four" into mutableNumbers again
  mutableNumbers.remove("one") // Removes "one" from mutableNumbers

  println("Mutable set after changes: $mutableNumbers") // Prints "Mutable set after changes: [two, three, four]", note that the order is not guaranteed
}

Here, we've also shown how to add and remove elements from mutable sets using the add() and remove() functions, respectively.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal