{
  "id": 44135,
  "title": "Guarded methods in OCaml",
  "url": "https://urgent.news/2026/08/02/guarded-methods-in-ocaml",
  "topic": "tech",
  "section": "Tech",
  "published": "2026-08-02T13:03:14.000Z",
  "source": {
    "name": "Lobsters",
    "slug": "lobsters",
    "url": "https://xvw.lol/en/articles/oop-refl.html"
  },
  "original_language": "en",
  "account": "Guarded methods in OCaml allow attaching constraints to specific methods based on the receiver's (self) type. Unfortunately, OCaml does not have a direct syntax to define such methods. This article explains how to encode them using a type equality witness. The concept is derived from languages like Java and OCaml, where parametric polymorphism enables constraining type variables. For instance, making a class generic by assuming a type variable is a subtype of another type allows constraining the constraint to specific methods. The main approaches to implement such methods include moving the method outside the class, using extension methods (as in Kotlin), or defining the method within the class with guards on the generic parameter. Despite the allure of guarded methods, no mainstream language currently supports their direct definition. However, OCaml can encode them using tools like type equality witnesses. Florian Angeletti, known as Octachron, was consulted for insights on implementing such methods in OCaml, despite the language's lack of native support.",
  "summary": null,
  "key_points": [
    "Guarded methods in OCaml attach constraints to specific methods based on receiver's type.",
    "OCaml lacks direct syntax for defining such methods.",
    "Type equality witness encodes guarded methods in OCaml."
  ],
  "editors_take": null,
  "illustration": "https://urgent.news/ill/44135.png",
  "coverage": {
    "outlets": 1,
    "also_reported_by": []
  },
  "ai_generated": true,
  "disclaimer": "Summaries, key points and the editor’s take are written by software from other outlets’ reporting and may contain errors — always check the linked original."
}