Skip to content
Kavachकवच

Records: Declaring

● Intermediate3 min

type Name { field: Type … } declares a record; Name(field: value, …) makes one.

type User {
    name: String
    age: Int
    city: String = "Pune"
}

fn main() {
    const asha = User(name: "Asha", age: 31)
    print("{asha.name}, {asha.age}, {asha.city}")
    const older = asha with { age: 32 }
    print("{asha.age} -> {older.age}")
    let copy = asha
    copy.city = "Delhi"
    print("{asha.city} / {copy.city}")
}

The program ran and printed:

kavach run record.kav

Asha, 31, Pune31 -> 32Pune / Delhi
record.kav: Kavach code, then what running it prints

Every field must be given when a record is made, unless it has a default. A missing one is caught at once:

type User {
    name: String
    age: Int
}

fn main() {
    const asha = User(name: "Asha")
    print(asha.name)
}

The compiler refused the program:

kavach run missing-field.kav

error: missing field `age` for `User`
missing-field.kav: Kavach code, then what running it prints