Search code examples
ocamlffibucklescript

Record with optional and mutable fields


In the docs: https://bucklescript.github.io/docs/en/object.html there are examples for a record with mutable fields and optional fields. When I try to use both it fails:

Compiles:

type person = {
  mutable age: int;
  job: string;
} [@@bs.deriving abstract]

let joe = person ~age:20 ~job:"teacher"
let () = ageSet joe 21

Adding the [@bs.optional] attribute:

type person = {
  mutable age: int;
  job: string [@bs.optional];
} [@@bs.deriving abstract]

let joe = person ~age:20 ~job:"teacher"
let () = ageSet joe 21

Error message:

Line 7, 20: This expression has type unit -> person but an expression was expected of type person

Line 7 is the ageSet line.

Am I missing anything here?


Solution

  • I re-read the documentation and this is the part I missed

    Note: now that your creation function contains optional fields, we mandate an unlabeled () at the end to indicate that you've finished applying the function.

    type person = {
      mutable age: int;
      job: string [@bs.optional];
    } [@@bs.deriving abstract]
    
    let joe = person ~age:20 ~job:"teacher" ()
    let () = ageSet joe 21