Created
July 26, 2019 03:12
-
-
Save ayago/6f0375270535342be91ce08afc8b8efa to your computer and use it in GitHub Desktop.
Lazy evaluation of function in Java
This file contains hidden or 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.math.BigDecimal; | |
import java.util.function.Function; | |
import static java.lang.String.format; | |
class SampleLazyEvaluation { | |
public static void main(String[] args) { | |
Function<String, BigDecimal> asBigDecimal = BigDecimal::new; | |
Function<Unit, BigDecimal> lazyAsBigDecimal = lazyApply(asBigDecimal, "3.00"); | |
System.out.println(format("Eager: %s, Lazy: %s", | |
asBigDecimal.apply("3.00"), lazyAsBigDecimal.apply(Unit.unit()))); | |
} | |
public static class Unit { | |
private static final Unit unit = new Unit(); | |
public static Unit unit(){ | |
return unit; | |
} | |
} | |
public static <A,B> Function<Unit, B> lazyApply(final Function<A, B> f, final A a){ | |
return unit -> f.apply(a); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment