Anotações de Tipo e Opcionais
Nesta página
Zolo infere o tipo de um binding a partir do lado direito da atribuição — na
maioria das vezes você não precisa escrever nada. Use a anotação let x: T = …
quando a inferência precisar de ajuda (arrays vazios, literais ambíguos) ou
quando quiser tornar o tipo explícito para quem lê o código:
Inferência vs anotação; arrays tipados e mapas como [int] e map.
// Feature: Explicit type annotation on bindings
// Syntax: `let name: Type = value`
// When to use: when inference is not enough (generics, ambiguous
// literals, optional nil types), or to keep the intent documented
// in the signature.
// Inference: the type comes from the RHS.
let inferred = 42 // int
let pi_inf = 3.14 // float
print(inferred)
print(pi_inf)
// Explicit annotation.
let count: int = 100
let ratio: float = 0.618
let label: str = "production"
let active: bool = true
print(count)
print(ratio)
print(label)
print(active)
// Optional type — `T?` allows `nil`.
let maybe_name: str? = nil
let maybe_age: int? = 30
print(maybe_name ?? "anonymous")
print(maybe_age ?? 0)
// Annotation on arrays and maps.
let scores: [int] = [10, 20, 30]
let prices: map = #{apple: 1.50, bread: 3.20}
print(scores)
print(prices)
// Useful when the RHS is generic/ambiguous (e.g. empty array).
let empty: [int] = []
print(empty)
Quando um valor pode legitimamente não existir, declare o tipo como T?.
Zolo permite nil somente em tipos opcionais — o compilador rejeita nil em
bindings sem ?. O operador ?? fornece um padrão quando o valor é nil:
T? permite nil; ?? devolve o lado direito quando o valor é nil; if let extrai o valor presente.
// Feature: Bindings with optional type `T?` and nil initialization
// Syntax: `let x: Type? = nil`
// When to use: when the value can legitimately be absent — search
// result, optional field, parse that may fail. In Zolo, `nil` is
// only allowed in types marked `T?`.
// Optional initialized as nil — filled in later.
var current_user: str? = nil
print(current_user ?? "anonymous") // anonymous
current_user = "Alice"
print(current_user ?? "anonymous") // Alice
// Result of a function that may fail.
fn find_user(id: int) -> str? {
if id == 1 { return "Alice" }
if id == 2 { return "Bob" }
return nil
}
let u1 = find_user(1)
let u3 = find_user(3)
print(u1 ?? "not found") // Alice
print(u3 ?? "not found") // not found
// Combining nullable + destructure (via `if let`).
if let name = find_user(2) {
print("found {name}") // found Bob
} else {
print("missing")
}
// Default sentinel via `??`.
let port: int? = nil
let actual_port = port ?? 8080
print(actual_port) // 8080
Desafio
Troque let maybe_name: str? = nil por let maybe_name: str = nil e veja o
erro de tipo que o compilador emite.
Veja também