Skip to content

Instantly share code, notes, and snippets.

@svieira
Created July 25, 2024 16:35
Show Gist options
  • Save svieira/9f8beeafb7bf4aa55d40c638532f4fd7 to your computer and use it in GitHub Desktop.
Save svieira/9f8beeafb7bf4aa55d40c638532f4fd7 to your computer and use it in GitHub Desktop.
Tagged types for Java 10+ using Intersection types
public class IntersectionTypes {
public static <S extends String & SafeString> void mainJava8() {
Worker.safeWork(
Validator.validate("Hello world!")
);
S s = Validator.validate("Intersection types must be aliased");
Worker.safeWork(s);
}
public static /* look Ma, no generics for type aliasing! */ void mainJava10plus() {
Worker.safeWork(
Validator.validate("Hello world!")
);
var s = Validator.validate("Intersection types can just use `var`");
Worker.safeWork(s);
}
}
interface StringValue {}
interface SafeString extends StringValue {}
interface UnsafeString extends StringValue {}
class Worker {
static <S extends String & SafeString> void safeWork(S s) {}
}
class Validator {
static <T extends String & SafeString> T validate(String s) {
// Check here, maybe throw an exception if invalid, and then if valid ...
return CastMagic.cast(s);
}
}
// https://www.gamlor.info/wordpress/2010/11/magic-cast-method-in-java/
class CastMagic {
private CastMagic(){}
public static <TSource,TTarget> TTarget cast(TSource toCast){
return (TTarget) toCast;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment