Átomo
17Rc
Controle de fluxo · Scala

recursão / @tailrec

Abrir na tabela

Definição

Em Scala, laços costumam virar funções recursivas. @tailrec garante que o compilador transforma a chamada final em um laço, sem estourar a pilha.

Exemplos

1. Laço como recursão
import scala.annotation.tailrec
@tailrec
def sumAmounts(orders: List[Order], acc: Double = 0): Double = orders match {
  case Nil     => acc
  case o :: tl => sumAmounts(tl, acc + o.amount)
}
2. Paginação recursiva
@tailrec
def fetchAll(page: Int, acc: Vector[Row]): Vector[Row] = {
  val batch = api.fetch(page)
  if (batch.isEmpty) acc else fetchAll(page + 1, acc ++ batch)
}
3. Inline com fold
val total = orders.foldLeft(0.0)((acc, o) => acc + o.amount)
val total2 = orders.map(_.amount).sum

No mesmo grupo