Saltar al contenido

Anotaciones de Tipo y Opcionales

En esta página

Zolo infiere el tipo de un binding a partir del lado derecho de la asignación — la mayoría de las veces no necesitas escribir nada. Usa la anotación let x: T = … cuando la inferencia necesite ayuda (arrays vacíos, literales ambiguos) o cuando quieras hacer el tipo explícito para quien lea el código:

Inferencia vs anotación; arrays tipados y mapas como [int] y map.

04-type-annotations.zolo
Playground
// 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)

Cuando un valor puede legítimamente no existir, declara el tipo como T?. Zolo permite nil solo en tipos opcionales — el compilador rechaza nil en bindings sin ?. El operador ?? proporciona un valor por defecto cuando el valor es nil:

T? permite nil; ?? devuelve el lado derecho cuando el valor es nil; if let extrae el valor presente.

10-nullable-init.zolo
Playground
// 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

Desafío

Cambia let maybe_name: str? = nil por let maybe_name: str = nil y observa el error de tipo que emite el compilador.

Buscar en Zolo

9 resultados

enespt-br