RFR: Initial push for type classes support

Maurizio Cimadamore mcimadamore at openjdk.org
Tue Jan 13 11:10:56 UTC 2026


This PR contains support for an experimental type classes feature.

> [!WARNING]
> Given the highly experimental nature of this work, nothing is settled in stone, and the comments below are mostly provided as a general guidance on how to use what's there.

For instance, given a record declaration like this:


record MyInt(int x) { }


We can define a new type class, for addition, using a regular interface, like so:


interface Sum<X> {
    X zero();
    X add(X a, X b);
}

And then define a _witness field_ of the type class `Sum` for the type `MyInt`, using the `__witness` keyword, like so:


__witness Sum<MyInt> SUM_MYINT = new Sum<>() {
       MyInt zero() { return new MyInt(0); }
       MyInt add(MyInt a, MyInt b) { return new MyInt(a.x + b.x); }
};

(For correctness, this field should be declared either in `Sum` or in `MyInt`)

Once defined, a witness can be _looked up_ using its type, like so:


Sum<MyInt> sum = Sum<MyInt>.__witness;
MyInt zero = sum.zero();
MyInt one = new MyInt(1);
assert sum.add(zero, one).equals(one);


This prototype contains other features, such as the declaration of witness methods, and the ability to perform witness lookups at runtime. For more examples, please refer to the tests under `test/langtools/tools/javac/typeClasses`.

-------------

Commit messages:
 - Tweak copyright for modified files
 - Update copyright of new files
 - Remove trailing whitespaces
 - Add missing files
 - Merge branch 'type_classes_clean' into type-classes
 - Initial push

Changes: https://git.openjdk.org/valhalla/pull/1886/files
  Webrev: https://webrevs.openjdk.org/?repo=valhalla&pr=1886&range=00
  Stats: 3205 lines in 55 files changed: 3165 ins; 1 del; 39 mod
  Patch: https://git.openjdk.org/valhalla/pull/1886.diff
  Fetch: git fetch https://git.openjdk.org/valhalla.git pull/1886/head:pull/1886

PR: https://git.openjdk.org/valhalla/pull/1886


More information about the valhalla-dev mailing list