// DOCS NAVIGATION
Retorno Implícito de Blocos_
SOURCE: content/docs/reference/04-avancado.md — 04 Avançado / 9. Retorno Implícito de Blocos / Implicit Block Return
PT-BR:
Em SpectraLang, blocos são expressões. O valor de um bloco é a última expressão que ele contém (sem ponto e vírgula). Isso vale para funções, if/else, match, e blocos anônimos.
EN-US:
In SpectraLang, blocks are expressions. The value of a block is its last expression (without a semicolon). This applies to functions, if/else, match, and anonymous blocks.
module blocos
public func main() {
// Bloco como expressão / Block as expression
let resultado = {
let a = 10
let b = 20
a + b // Retorno implícito do bloco: 30 / Implicit block return: 30
}
// resultado == 30
// if como expressão / if as expression
let max = if 10 > 5 { 10 } else { 5 }
// max == 10
// match como expressão / match as expression
let descricao = match resultado {
when 0..=10 then "baixo",
when 11..=50 then "médio",
otherwise then "alto"
}
// descricao == "médio"
// Função com retorno implícito / Function with implicit return
println(calcular(5, 3))
// 8
}
// Retorno implícito na última linha / Implicit return on last line
func calcular(a: int, b: int) returns int {
let soma = a + b
soma // Retorna soma / Returns soma
}
// Retorno implícito em ramo if / Implicit return in if branch
func classificar(n: int) returns string {
if n < 0 {
"negativo"
} else if n == 0 {
"zero"
} else {
"positivo"
}
}
Regras Importantes / Important Rules
PT-BR:
- A expressão final termina por quebra de linha ou
}e produz retorno implícito return exprfunciona em qualquer ponto da função (inclui retorno antecipado)
EN-US:
- The final expression ends at a line break or
}and produces an implicit return return exprworks anywhere in a function (includes early return)
func exemplo1() returns int {
42 // Retorna 42 / Returns 42
}
func exemplo2() returns int {
42
// 42 descartado, retorna unit — ERRO DE TIPO / 42 discarded, returns unit — TYPE ERROR
// O compilador lançará um erro pois a assinatura diz returns int mas o bloco retorna unit
}
func exemplo3() returns int {
let x = 42
return x
// Retorno explícito / Explicit return
// O código após return nunca será executado / Code after return is never reached
}
Próximo / Next: 05 — Biblioteca Padrão / Standard Library
Anterior / Previous: 03 — Tipos Compostos / Composite Types