Module and Class in OCaml

The main difference between Module and Class is that you don't instantiate a module.

A module is basically just a "drawer" where you can put types, functions, other modules, etc... It is just here to order your code. This drawer is however really powerful thanks to functors.

A class, on the other hand, exists to be instantiated. They contains variables and methods. You can create an object from a class, and each object contains its own variable and methods (as defined in the class).

In practice, using a module will be a good solution most of the time. A class can be useful when you need inheritance (widgets for example).


From a practical perspective dynamic lookup lets you have different objects with the same method without specifying to which class/module it belongs. It helps you when using inheritance.

For example, let's use two data structures: SingleList and DoubleLinkedList, which, both, inherit from List and have the method pop. Each class has its own implementation of the method (because of the 'override').

So, when you want to call it, the lookup of the method is done at runtime (a.k.a. dynamically) when you do a list#pop.

If you were using modules you would have to use SingleList.pop list or DoubleLinkedList.pop list.

EDIT: As @Majestic12 said, most of the time, OCaml users tend to use modules over classes. Using the second when they need inheritance or instances (check his answer).

I wanted to make the description practical as you seem new to OCaml.

Hope it can help you.

Tags:

Ocaml