|
1 | 1 | # Type Class resolution for Java |
2 | 2 |
|
3 | 3 | See: https://garciat.com/posts/java-type-classes/ |
| 4 | + |
| 5 | +The core API of this library is: |
| 6 | + |
| 7 | +```java |
| 8 | +@interface TypeClass { |
| 9 | + @interface Witness {} |
| 10 | +} |
| 11 | + |
| 12 | +public class TypeClasses { |
| 13 | + public static <T> T witness(Ty<T> ty); |
| 14 | +} |
| 15 | +``` |
| 16 | + |
| 17 | +Where: |
| 18 | + |
| 19 | +- For a witness type `C<T1, T2, ..., Tn>`, `witness()` looks for witness |
| 20 | + constructors in `C` and `T1, T2, ..., Tn`. |
| 21 | +- Witness constructors for a type `T` are its `public static` methods annotated |
| 22 | + with `@TypeClass.Witness`. |
| 23 | +- For a witness constructor `C<T> ctor(D1, D2, ..., Dn)`, the witness |
| 24 | + dependencies `D1, D2, ..., Dn` are resolved recursively. |
| 25 | +- Overlapping instances behavior per |
| 26 | + [this spec](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html#overlapping-instances), |
| 27 | + except for the incoherent instances part. |
| 28 | +- Resolution fails when multiple witness constructors exist for a witness type, |
| 29 | + after applying overlapping instances reduction. |
| 30 | +- Resolution fails when a witness constructor for a witness type cannot be |
| 31 | + found. |
| 32 | +- Witness summoning is the result of recursively invoking witness constructors |
| 33 | + up their respective dependency trees. |
| 34 | +- `T witness(Ty<T>)` summons a witness of type `T` or fails with a runtime |
| 35 | + exception of type `TypeClasses.WitnessResolutionException`. |
| 36 | + |
| 37 | +Now, there are multiple built-in type classes and types in the `classes` and |
| 38 | +`types` packages, respectively. Their usage is **completely optional**. If your |
| 39 | +code does not refer to any of the types defined there, then witness resolution |
| 40 | +will not take them into account. As mentioned above, the resolution of a witness |
| 41 | +`C<T>` is completely local to the definitions of `C` and `T`. |
| 42 | + |
| 43 | +For examples, check out the |
| 44 | +[ExamplesTest.java](https://github.com/Garciat/java-type-classes/blob/main/src/test/java/com/garciat/typeclasses/ExamplesTest.java) |
| 45 | +file and its respective imports. |
0 commit comments