0Pricing
Scala for Backend Engineering & Functional Programming · Lektion

Vertiefung zu unveränderlichen Collections

Erkunden Sie grundlegende unveränderliche Collections wie List, Map und Set und lernen Sie deren effiziente Verwendung kennen.

Vertiefung zu unveränderlichen Collections ist eine kostenlose Scala for Backend Engineering & Functional Programming-Lektion auf CoddyKit. Dies ist Lektion 1 von 3. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Scala for Backend Engineering & Functional Programming-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Scala for Backend Engineering & Functional Programming-Kurs umfasst insgesamt 3 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

Immutable Collections: Overview

Welcome to immutable collections! In Scala, these are foundational for writing robust, concurrent, and predictable code, especially in functional programming.

We'll explore fundamental types like List, Map, and Set, focusing on their efficient and safe usage.

Why Immutability Matters

Immutability means that once a collection is created, it cannot be changed. Any operation that seems to 'modify' it actually returns a new collection.

  • Predictability: Easier to reason about code.
  • Thread Safety: No need for locks as data never changes.
  • No Side Effects: Operations won't unexpectedly alter data elsewhere.

Scala Lists: Ordered Sequences

A List in Scala is an immutable, ordered sequence of elements of the same type. It's ideal for sequential data where order matters.

You can create a list by simply enumerating its elements.

object Main {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 2, 3, 4, 5)
    val fruits = List("apple", "banana", "cherry")
    println(s"Numbers list: $numbers")
    println(s"Fruits list: $fruits")
  }
}

List Operations: Head, Tail, Cons

Lists offer common operations like getting the head (first element) and tail (rest of the list). The :: (cons) operator is used to prepend an element, creating a new list.

object Main {
  def main(args: Array[String]): Unit = {
    val numbers = List(10, 20, 30)
    println(s"Original list: $numbers")
    println(s"Head of list: ${numbers.head}") // 10
    println(s"Tail of list: ${numbers.tail}") // List(20, 30)
    val newList = 5 :: numbers // Prepend 5
    println(s"List with 5 prepended: $newList")
  }
}

Scala Maps: Key-Value Associations

A Map is an immutable collection that stores key-value pairs. Each key is unique and maps to a single value. Maps are excellent for looking up values by a specific key.

object Main {
  def main(args: Array[String]): Unit = {
    val ages = Map("Alice" -> 30, "Bob" -> 25, "Charlie" -> 35)
    val codes = Map(1 -> "One", 2 -> "Two")
    println(s"Ages map: $ages")
    println(s"Codes map: $codes")
  }
}

Map Operations: Access & Update

You can access values in a Map using its key. To 'update' or 'add' a key-value pair, you create a new map with the changes, leaving the original map untouched.

object Main {
  def main(args: Array[String]): Unit = {
    val ages = Map("Alice" -> 30, "Bob" -> 25)
    println(s"Original ages: $ages")
    println(s"Bob's age: ${ages("Bob")}")
    val updatedAges = ages + ("Charlie" -> 35) // Add new pair
    println(s"Ages after adding Charlie: $updatedAges")
    val changedAges = updatedAges + ("Alice" -> 31) // Update Alice's age
    println(s"Ages after updating Alice: $changedAges")
  }
}

Scala Sets: Unique Elements

A Set is an immutable collection of unique elements. Unlike Lists, the order of elements in a Set is not guaranteed, and duplicate elements are automatically ignored.

Sets are perfect for checking membership or ensuring uniqueness.

object Main {
  def main(args: Array[String]): Unit = {
    val numbers = Set(1, 2, 2, 3, 4, 3, 5)
    val letters = Set('a', 'b', 'a')
    println(s"Unique numbers: $numbers")
    println(s"Unique letters: $letters")
  }
}

Set Operations: Add, Remove, Union

Similar to Lists and Maps, operations on Sets like adding or removing elements also return a new Set. You can also perform set theory operations like union (combining sets).

object Main {
  def main(args: Array[String]): Unit = {
    val setA = Set(1, 2, 3)
    val setB = Set(3, 4, 5)
    println(s"Set A: $setA")
    println(s"Set B: $setB")
    val addedSet = setA + 4 // Add element
    println(s"Set A + 4: $addedSet")
    val removedSet = setA - 2 // Remove element
    println(s"Set A - 2: $removedSet")
    val unionSet = setA union setB // Combine sets
    println(s"Set A union Set B: $unionSet")
  }
}

Immutability: Original Remains

It's crucial to remember that all 'modifying' operations on Scala's immutable collections return a new collection. The original collection is never changed.

This behavior is a cornerstone of functional programming in Scala.

object Main {
  def main(args: Array[String]): Unit = {
    val originalList = List(10, 20, 30)
    println(s"Original List: $originalList")
    val doubledList = originalList.map(_ * 2) // map returns a NEW list
    println(s"List after map: $doubledList")
    println(s"Original list is still: $originalList") // Unchanged!
  }
}

Check Your Understanding

Consider the following Scala code snippet:

val mySet = Set(1, 2, 3)
val newSet = mySet + 3 + 4
val finalSet = newSet - 2

What will be the value of mySet after these operations?

Recap: Immutable Collections

You've taken a deep dive into Scala's fundamental immutable collections:

  • Lists: Ordered sequences, good for sequential data.
  • Maps: Key-value pairs, efficient for lookups.
  • Sets: Unique elements, great for membership checks.

The key takeaway is immutability: operations always return new collections, ensuring predictability and safety.

Häufig gestellte Fragen

Ist die Lektion „Vertiefung zu unveränderlichen Collections“ kostenlos?

Ja — der vollständige Text von „Vertiefung zu unveränderlichen Collections“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Scala for Backend Engineering & Functional Programming-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Scala for Backend Engineering & Functional Programming-Kurs umfasst insgesamt 3 Lektionen.

Was lerne ich in „Vertiefung zu unveränderlichen Collections“?

Erkunden Sie grundlegende unveränderliche Collections wie List, Map und Set und lernen Sie deren effiziente Verwendung kennen. Du übst Scala for Backend Engineering & Functional Programming mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Scala for Backend Engineering & Functional Programming zu starten?

Keine Vorkenntnisse erforderlich. Scala for Backend Engineering & Functional Programming auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 1 von 3.

Wie lange dauert die Lektion „Vertiefung zu unveränderlichen Collections“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Scala for Backend Engineering & Functional Programming-Lektion Code schreiben und ausführen?

Ja. Jede Scala for Backend Engineering & Functional Programming-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Vertiefung zu unveränderlichen Collections
  2. Funktionale Operationen auf Collections
  3. Option, Try und Either für Fehler
← Zurück zu Scala for Backend Engineering & Functional Programming