How to create an object in ReasonML?


Hello there,

I am looking for an example of creating an object in ReasonML/Bucklescript. I have been hitting my head trying to create an instance of the class that is defined in the documentation on the Bucklescript site, but I’m not making any progress. I am going to skip ahead in “Real World OCaml” tonight and see if I can make any sense of the chapter on objects.

Other questions I have are:

  • Do I have to define methods inline?
  • Do classes get compiled into JS objects or ES6 classes?
  • Does the Bucklescript compiler fully support the object-oriented features of OCaml?

I’ll post the example code here as well:

class type _rect =
    [@bs.set] pub height: int;
    [@bs.set] pub width: int;
    pub draw: unit => unit

type rect = Js.t(_rect);

  1. yes you can define functions separately (see code example)
  2. js objects, if you’re doing @bs.obj, otherwise the representation is very different (see code example)
  3. Yup! If you’re using normal ocaml objects.

See this example for a comparison between js-style objects and ocaml objects in bucklescript: try reason snippet


Nice looking for this exact example @jaredly . BTW big fan of reason town.
After hearing your podcast decided to write a microservice in reasonml.