0Pricing
Scala for Backend Engineering & Functional Programming · Aula

Operações funcionais em coleções

Domine operações funcionais comuns, como map, filter, fold e reduce, para transformar dados.

Operações funcionais em coleções é uma aula grátis de Scala for Backend Engineering & Functional Programming no CoddyKit. Esta é a aula 2 de 3. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Scala for Backend Engineering & Functional Programming, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Scala for Backend Engineering & Functional Programming inclui 3 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Functional Ops: Why Use Them?

Functional operations on collections help you transform and combine data without changing the original collection. This approach promotes immutability and makes your code easier to read and test.

We'll explore key operations like map, filter, reduce, and fold.

Transform with `map`

The map operation applies a function to each element of a collection and returns a new collection with the transformed results. The original collection remains unchanged.

Try running this example:

object Main {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 2, 3, 4)
    val doubled = numbers.map(n => n * 2)
    println(s"Original: $numbers")
    println(s"Doubled: $doubled")
  }
}

`map` with Different Types

map is very flexible! You can transform elements into a completely different type. Here, we convert numbers to strings, or get string lengths.

Notice how the result is a List[Int], even though the input was List[String].

object Main {
  def main(args: Array[String]): Unit = {
    val names = List("Alice", "Bob", "Charlie")
    val lengths = names.map(name => name.length)
    println(s"Names: $names")
    println(s"Lengths: $lengths")
  }
}

Select with `filter`

The filter operation creates a new collection containing only the elements that satisfy a given condition (a predicate function). It "filters out" unwanted elements.

Let's find the even numbers:

object Main {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 2, 3, 4, 5, 6)
    val evens = numbers.filter(n => n % 2 == 0)
    println(s"Original: $numbers")
    println(s"Evens: $evens")
  }
}

More `filter` Examples

You can use any boolean expression as your filter condition. Let's filter a list of words to keep only those longer than 4 characters.

object Main {
  def main(args: Array[String]): Unit = {
    val words = List("apple", "cat", "banana", "dog", "elephant")
    val longWords = words.filter(w => w.length > 4)
    println(s"Words: $words")
    println(s"Long words: $longWords")
  }
}

Combine with `reduce`

The reduce operation combines all elements of a collection into a single result. It takes a binary operation (a function that takes two arguments and returns one) and applies it cumulatively.

Here, we sum all elements:

object Main {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 2, 3, 4)
    val sum = numbers.reduce((a, b) => a + b)
    println(s"Numbers: $numbers")
    println(s"Sum: $sum")
  }
}

`reduce` for Product & Max

reduce can perform various aggregations. We can calculate the product of numbers or find the maximum value.

Note: reduce will throw an error on an empty collection.

object Main {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 5, 2, 8)
    val product = numbers.reduce((a, b) => a * b)
    val maxNum = numbers.reduce((a, b) => if (a > b) a else b)
    println(s"Numbers: $numbers")
    println(s"Product: $product")
    println(s"Max: $maxNum")
  }
}

`fold`: Initial Value Power

fold is similar to reduce but with an important difference: it takes an initial value (also called an "accumulator"). This makes it safe for empty collections and allows for different result types.

Let's sum numbers, starting from 10:

object Main {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 2, 3)
    // foldLeft(initialValue)(operation)
    val sumWithInitial = numbers.foldLeft(10)((acc, n) => acc + n)
    println(s"Numbers: $numbers")
    println(s"Sum (starting from 10): $sumWithInitial")
  }
}

Direction: `foldLeft` vs `foldRight`

Scala offers foldLeft and foldRight. They differ in the order of processing elements and how the accumulator is passed.

  • foldLeft(initial)(op): Processes left-to-right.
  • foldRight(initial)(op): Processes right-to-left.

For operations like string concatenation, the direction matters!

object Main {
  def main(args: Array[String]): Unit = {
    val chars = List('a', 'b', 'c')
    val leftFold = chars.foldLeft("")((acc, c) => acc + c)
    val rightFold = chars.foldRight("")((c, acc) => acc + c)
    println(s"Chars: $chars")
    println(s"foldLeft: $leftFold") // Output: abc
    println(s"foldRight: $rightFold") // Output: abc (due to string append order)

    // Example where order matters: (acc, char) => char + acc
    val rightFoldReversed = chars.foldRight("")((c, acc) => c + acc)
    println(s"foldRight (char + acc): $rightFoldReversed") // Output: abc

    // A common example where order matters is for operations like subtraction or division, but string concatenation also shows it.
  }
}

Functional Operations Check

Consider the following Scala code snippet:

val data = List(10, 20, 30, 40)
val result1 = data.map(x => x / 10)
val result2 = data.filter(x => x > 25)
val result3 = data.reduce((a, b) => a + b)

Which of the following statements are TRUE about the results?

Recap: Power of Functional Ops

You've mastered essential functional operations!

  • map transforms each element.
  • filter selects elements based on a condition.
  • reduce combines elements into a single result (requires non-empty collection).
  • fold combines elements with an initial value (safe for empty collections).

These operations are key for writing concise, immutable, and powerful Scala code. Next, we'll explore robust error handling using Option, Try, and Either.

Perguntas Frequentes

A aula “Operações funcionais em coleções” é grátis?

Sim — o texto completo de “Operações funcionais em coleções” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Scala for Backend Engineering & Functional Programming, atualize para CoddyKit PRO. O curso de Scala for Backend Engineering & Functional Programming inclui 3 aulas no total.

O que vou aprender em “Operações funcionais em coleções”?

Domine operações funcionais comuns, como map, filter, fold e reduce, para transformar dados. Você pratica Scala for Backend Engineering & Functional Programming com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Scala for Backend Engineering & Functional Programming?

Nenhuma experiência prévia é necessária. Scala for Backend Engineering & Functional Programming no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 3.

Quanto tempo leva a aula “Operações funcionais em coleções”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Scala for Backend Engineering & Functional Programming?

Sim. Cada aula de Scala for Backend Engineering & Functional Programming inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Mergulho profundo em coleções imutáveis
  2. Operações funcionais em coleções
  3. Option, Try e Either para erros
← Voltar para Scala for Backend Engineering & Functional Programming