2

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?

glennsl
  • 28,186
  • 12
  • 57
  • 75
kunigami
  • 3,046
  • 4
  • 26
  • 42

1 Answers1

2

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
kunigami
  • 3,046
  • 4
  • 26
  • 42
  • Ocaml functions require the last argument to always be non optional. So when you have a function where that isn't the case the general solution is to add a dummy unit argument. bs.optional has no choice but to do that here. – Goswin von Brederlow Jun 28 '18 at 10:10