Search code examples
oopocamlreason

OOP - How does one create a class in ReasonML


I know that in OCaml, one can create a class doing the following:

class stack_of_ints =
  object (self)
    val mutable the_list = ( [] : int list ) (* instance variable *)
    method push x =                        (* push method *)
      the_list <- x :: the_list
  end;;

However, I have been struggling on finding documentation on how to do it in Reason. Thank you.


Solution

  • Classes and objects aren't very well documented because these features add a lot of complexity for (usually) very little benefit compared to a more idiomatic approach. But if you know the OCaml syntax for something, you can always see what the Reason equivalent is by converting it with the online "Try Reason" playground. See your example here, which gives us this:

    class stack_of_ints = {
      as self;
      val mutable the_list: list int = []; /* instance variable */
      pub push x =>
        /* push method */
        the_list = [x, ...the_list];
    };