0Pricing
Scala for Backend Engineering & Functional Programming · Aula

Option, Try e Either para erros

Implemente um tratamento robusto de erros usando `Option` para ausência de valor, `Try` para exceções e `Either` para caminhos distintos de falha e sucesso.

Option, Try e Either para erros é uma aula grátis de Scala for Backend Engineering & Functional Programming no CoddyKit. Esta é a aula 3 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.

Handling Errors Gracefully

In programming, things don't always go as planned. Files might not exist, network requests could fail, or calculations might lead to invalid results.

  • How do we write robust code that can handle these situations gracefully?
  • Scala provides powerful tools to manage errors and missing values without resorting to `null` or throwing exceptions everywhere.

The Problem with Null

Many languages use null to represent the absence of a value. However, null is a common source of bugs like the dreaded NullPointerException.

Scala discourages the use of null. Instead, it offers types that explicitly state whether a value might be missing, making your code safer and easier to understand.

Introducing Scala Option

Option[A] is a container that can hold either a value of type A (represented by Some[A]) or no value at all (represented by None).

  • It forces you to consider the case where a value might be absent.
  • This prevents unexpected NullPointerExceptions and makes your code more explicit.

Option in Action: Some & None

Let's see how Option works. We'll define a function that might return a name or might not, depending on an ID.

object Main {
  def findUser(id: Int): Option[String] = {
    if (id == 1) Some("Alice")
    else None
  }

  def main(args: Array[String]): Unit = {
    val user1 = findUser(1) // Some("Alice")
    val user2 = findUser(2) // None

    println(s"User 1: $user1")
    println(s"User 2: $user2")
  }
}

Working with Option: map & getOrElse

You can transform the value inside an Option using map, or provide a default value if it's None using getOrElse.

object Main {
  def findUser(id: Int): Option[String] = {
    if (id == 1) Some("Alice")
    else None
  }

  def main(args: Array[String]): Unit = {
    val userGreeting = findUser(1).map(name => s"Hello, $name!")
    val defaultGreeting = findUser(2).map(name => s"Hello, $name!").getOrElse("Hello, Guest!")

    println(s"User greeting: $userGreeting")
    println(s"Default greeting: $defaultGreeting")
  }
}

Introducing Scala Try

While Option handles missing values, Try[A] is designed to handle computations that might throw an exception.

  • A Try can be either a Success[A] (if the computation completes normally) or a Failure[Throwable] (if an exception occurs).
  • It encapsulates exceptions, allowing you to deal with them functionally.

Try in Action: Success & Failure

Let's define a function that might throw an exception (e.g., division by zero) and wrap its execution in a Try.

import scala.util.{Try, Success, Failure}

object Main {
  def divide(a: Int, b: Int): Try[Int] = Try {
    a / b
  }

  def main(args: Array[String]): Unit = {
    val result1 = divide(10, 2) // Success(5)
    val result2 = divide(10, 0) // Failure(java.lang.ArithmeticException: / by zero)

    println(s"Result 1: $result1")
    println(s"Result 2: $result2")
  }
}

Working with Try: recover & fold

Try offers methods like recover to handle specific exceptions or fold to process both success and failure cases cleanly.

import scala.util.{Try, Success, Failure}

object Main {
  def parseNumber(s: String): Try[Int] = Try(s.toInt)

  def main(args: Array[String]): Unit = {
    val num1 = parseNumber("123").getOrElse(0)
    val num2 = parseNumber("abc").getOrElse(0)

    val message = parseNumber("456").fold(
      ex => s"Failed to parse: ${ex.getMessage}",
      num => s"Parsed number: $num"
    )

    println(s"Parsed num1: $num1")
    println(s"Parsed num2: $num2")
    println(s"Message: $message")
  }
}

Introducing Scala Either

Either[L, R] is a type that represents one of two possible values. By convention:

  • Left[L] represents a failure (or error type L).
  • Right[R] represents a success (or result type R).

Unlike Try, Either allows you to specify a meaningful type for your error, not just a Throwable.

Either in Action: Left & Right

Here's a function that validates an email. It returns either a String error message (Left) or the validated email (Right).

object Main {
  def validateEmail(email: String): Either[String, String] = {
    if (email.contains("@") && email.contains(".")) Right(email)
    else Left("Invalid email format")
  }

  def main(args: Array[String]): Unit = {
    val email1 = validateEmail("test@example.com") // Right("test@example.com")
    val email2 = validateEmail("invalid-email")   // Left("Invalid email format")

    println(s"Email 1: $email1")
    println(s"Email 2: $email2")
  }
}

Quick Check: Error Handling

You are writing a function that reads a configuration value from a map. If the key exists, you want to convert its string value to an integer. If the key is missing or the conversion fails, you want to return a default value of 0.

Which combination of Scala types and methods would be most appropriate for this task?

Recap: Option, Try, Either

We've explored three powerful Scala types for robust error handling:

  • Option[A]: For handling the absence of a value (Some[A] or None).
  • Try[A]: For encapsulating computations that might throw exceptions (Success[A] or Failure[Throwable]).
  • Either[L, R]: For representing two distinct outcomes, typically a failure type L and a success type R (Left[L] or Right[R]).

Using these types makes your Scala code safer, more explicit, and more functional!

Perguntas Frequentes

A aula “Option, Try e Either para erros” é grátis?

Sim — o texto completo de “Option, Try e Either para erros” é 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 “Option, Try e Either para erros”?

Implemente um tratamento robusto de erros usando `Option` para ausência de valor, `Try` para exceções e `Either` para caminhos distintos de falha e sucesso. 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 3 de 3.

Quanto tempo leva a aula “Option, Try e Either para erros”?

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