Records
Reason’s records are like JS objects.
They are fast, immutable by default, have fuxed types.
type boy = {
name: string,
age: int
}
boy is a record and has age and name properties.
let neighborsKid = {
name: "Ken",
age: 10
}
neighborsKid get’s infered to boy
We can access the boy’s name with a dot notation, Just like in Javascript
let name = neighborsKid.name
Updating records.
The immutable way
Records are immutable by default, and by default updates happen by creating new tuples with the updated values.
For instance lets say the neighborsKid performed a heroic act of saving a cat from a burning tree and the queen of England decided to make him a knight. So his new name will be Sir Ken
let neighborsKidAfterKnighthood = {...neighborsKid, name: "Sir " ++ neighborsKid.name}
The 3 dots are known as spread operator. If you are familiar with es2015 then you know what they are.
The mutable way
Record fields can be mutable but not by default. to make a record field mutable use the mutable keyword when creating the record type.
type boy = {
mutable name: string,
age: int
}
let neighborsKid = {
name: "Ken",
age: 10
}
neighborsKid.name = "Sir " ++ neighborsKid.name
Final Note.
Lets assume that 3 years later we adopted a cat and named it after Ken, well without the Sir.
type cat = { name: string, age: int }
Okay, now since both have ages, we can compare and see the age difference between Ken and the cat.
let getAge = (entity) => entity.age
So getAge takes a record as a param and returns the age of the record.
So lets define our cat and get the age difference
let kenCat: cat = {
name: "KenCat",
age: 3
}
let ageDiff = getAge(kenCat) - getAge(neighborsKidAfterKnighthood)
This doesn’t work as expected. The compiler complains that getAge expected a record of type cat but type boy was provided, even though they have the same shape. A function cannot take any record type even when the records in question have the same properties. Functions take a specific record.