Last active
November 25, 2025 23:10
-
-
Save justADeni/35091357bb139069560f892fa6e4a584 to your computer and use it in GitHub Desktop.
Lazy Supplier
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.util.function.Supplier; | |
| @FunctionalInterface | |
| interface Lazy<T> extends Supplier<T> { | |
| T get(); | |
| static <T> Lazy<T> of(Supplier<T> supplier) { | |
| return new LazyImpl<>(supplier); | |
| } | |
| } | |
| final class LazyImpl<T> implements Lazy<T> { | |
| private final Supplier<T> supplier; | |
| private T value; | |
| LazyImpl(Supplier<T> supplier) { | |
| this.supplier = supplier; | |
| } | |
| @Override | |
| public T get() { | |
| if (value == null) value = supplier.get(); | |
| return value; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: Not thread-safe. If you want thread safety, you need to synchronize it yourself.