Classes, inheritance, and modules

Learning objective

  • Structure Lucia programs with classes and multi-file imports.

Key syntax

class Animal {
    let name: string = "unknown";
    const kind: string = "animal";
    constructor(name: string) { this.name = name; }
}

class Dog extends Animal {
    func bark() { print(this.name); }
}

Examples

  • Import syntax: import "./models/pet.lucia";.
  • Import syntax also supports project-local files such as import "Palo.lucia";.
  • Single inheritance with extends.
  • Class fields may use default initializers.
  • Class fields may be declared with const when they must not be reassigned.
  • Use this for instance state.

Method and field access inside classes

  • Explicit style:
func toString(): string {
    return this.obtenerNombreValor() + " " + this.obtenerNombrePalo();
}
  • Implicit style (allowed):
func toString(): string {
    return obtenerNombreValor() + " " + obtenerNombrePalo();
}

Indexed assignment in methods

func mezclarMazo(): void {
    let n: int = len(this.mazo);
    for (let i = 0; i < n; i = i + 1) {
        let j: int = random(0, n - 1);
        let temp: Carta = this.mazo[i];
        this.mazo[i] = this.mazo[j];
        this.mazo[j] = temp;
    }
}

Common mistakes

  • Forgetting that const class fields require an initializer.
  • Reassigning a const field after declaration.
  • Unknown class/function due to missing imports.
  • Circular imports between files.
  • Using list.length() instead of len(list).

Suggested practice

  • Split a small domain model into 2-3 files using imports, inheritance, and initialized class fields.
  • declarations-let-const
  • diagnostics