Created
April 20, 2017 19:12
-
-
Save jbgi/d6b677d084fafc641fe01f7ffd00591c to your computer and use it in GitHub Desktop.
Zero-cost newtype in Java, based on https://failex.blogspot.ch/2017/04/the-high-cost-of-anyval-subclasses.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import org.derive4j.hkt.__; | |
public abstract class Label<T> { | |
private Label(){} | |
public abstract T apply(String s); | |
public abstract String unwrap(T lbl); | |
public abstract <f> __<f, String> subst(__<f, T> fa); | |
static Label<?> Label = new Label<String>() { | |
@Override | |
public String apply(String s) { | |
return s; | |
} | |
@Override | |
public String unwrap(String lbl) { | |
return lbl; | |
} | |
@Override | |
public <f> __<f, String> subst(__<f, String> fa) { | |
return fa; | |
} | |
}; | |
public static void main(String[] args) throws IOException { | |
program(Label).run(); | |
} | |
// "Slight" inconvenience vs scala: you have to write your program inside method(s) parametrized by the Label(s): | |
static <T> IO<Unit> program(Label<T> Label) { | |
class Toto { | |
private final T wrapped; | |
Toto(T wrapped){this.wrapped = wrapped;} | |
} | |
Toto toto = new Toto(Label.apply("Hello World")); | |
String unwrapped = Label.unwrap(toto.wrapped); | |
return IO.effect(() -> System.out.println(unwrapped)); | |
} | |
} |
Your example use a stateless lambda, but in the general case object instantiation via lambda is not cost-free. But yes it is simpler and actually practical.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why not simply :