Skip to content
Kavachकवच

Records: Updating with with

● Intermediate3 min

record with { field: value } makes a copy with some fields changed.

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

asha with { age: 32 } is a new User; asha is still 31. Through a let, you can also assign a field directly, as copy.city = "Delhi" does: that changes only copy.