0Pricing
Scala for Backend Engineering & Functional Programming · Aula

Expressões em vez de instruções

Tudo é uma expressão.

Expressões em vez de instruções é uma aula grátis de Scala for Backend Engineering & Functional Programming no CoddyKit. Esta é a aula 3 de 4. 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 4 aulas no total.

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

Expressions vs Statements

A statement does something but returns nothing useful. An expression evaluates to a value.

In Scala, almost everything is an expression. This is a core idea that shapes how you write code.

if Is an Expression

In many languages if is a statement. In Scala, if/else returns a value, so you can assign it directly to a val.

No need for a separate variable assigned in each branch.

object Main {
  def main(args: Array[String]): Unit = {
    val temp = 30
    val label = if (temp > 25) "hot" else "mild"
    println(label)
  }
}

Blocks Are Expressions

A block { ... } is an expression too. Its value is the value of its last line.

So you can compute intermediate values, then end with the result.

object Main {
  def main(args: Array[String]): Unit = {
    val result = {
      val a = 2
      val b = 3
      a * b
    }
    println(result)
  }
}

match Is an Expression

Pattern matching with match also returns a value. Each branch produces a result, and the whole expression yields the matched branch's value.

object Main {
  def main(args: Array[String]): Unit = {
    val day = 3
    val name = day match {
      case 1 => "Mon"
      case 2 => "Tue"
      case 3 => "Wed"
      case _ => "Other"
    }
    println(name)
  }
}

The Unit Type

Some expressions exist only for their side effect, like println. They return Unit, written ().

Unit is similar to void in other languages but is still a real value.

object Main {
  def main(args: Array[String]): Unit = {
    val nothing: Unit = println("side effect")
    println(nothing)
  }
}

Returning From Functions

Because the body of a function is an expression, the last expression is its return value. You rarely need the return keyword.

Here the function body is a single expression.

object Main {
  def max(a: Int, b: Int): Int = if (a > b) a else b
  def main(args: Array[String]): Unit = {
    println(max(7, 4))
  }
}

Expression-Oriented Functions

A function can be a block expression whose last line is the result. This keeps logic compact and avoids mutable temporaries.

object Main {
  def discount(price: Double): Double = {
    val rate = if (price > 100) 0.2 else 0.1
    price * (1 - rate)
  }
  def main(args: Array[String]): Unit = {
    println(discount(150.0))
  }
}

No Need for Mutation

Because if and match are expressions, you can assign their result to a val instead of mutating a var.

This leads to cleaner, more functional code.

object Main {
  def main(args: Array[String]): Unit = {
    val score = 85
    val grade = if (score >= 90) "A"
      else if (score >= 80) "B"
      else "C"
    println(grade)
  }
}

Composing Expressions

Because everything returns a value, expressions nest and compose freely. The output of one becomes the input of another.

This composability is a big reason Scala feels expressive.

object Main {
  def main(args: Array[String]): Unit = {
    val n = 7
    val message = "n is " + (if (n % 2 == 0) "even" else "odd")
    println(message)
  }
}

Why It Matters

Expression-oriented code:

  • Reduces the need for mutable variables
  • Makes the flow of values explicit
  • Composes naturally into larger programs
  • Pairs perfectly with immutability

All Together

Here a block expression contains an if expression, all assigned to a single immutable result.

object Main {
  def main(args: Array[String]): Unit = {
    val total = {
      val items = 3
      val each = 12
      val raw = items * each
      if (raw > 30) raw - 5 else raw
    }
    println(total)
  }
}

Quick Check

Check your grasp of expressions.

Recap

You learned that in Scala nearly everything is an expression:

  • if/else, match, and blocks all return values
  • A block's value is its last expression
  • Side-effecting expressions return Unit (())
  • The last expression of a function is its return value
  • This reduces mutation and improves composability

Perguntas Frequentes

A aula “Expressões em vez de instruções” é grátis?

Sim — o texto completo de “Expressões em vez de instruçõ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 4 aulas no total.

O que vou aprender em “Expressões em vez de instruções”?

Tudo é uma expressão. 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 4.

Quanto tempo leva a aula “Expressões em vez de instruçõ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. Usando a REPL
  2. val, var e tipos
  3. Expressões em vez de instruções
  4. Interpolação de strings
← Voltar para Scala for Backend Engineering & Functional Programming