From e861d0343bab244992de29f3cd9c49a8d1b2c81b Mon Sep 17 00:00:00 2001 From: Oliver Gierke Date: Tue, 28 Feb 2017 18:45:10 +0100 Subject: [PATCH] DATACMNS-867 - Additions to Lazy. Added mapping functions to Lazy. --- .../org/springframework/data/util/Lazy.java | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/springframework/data/util/Lazy.java b/src/main/java/org/springframework/data/util/Lazy.java index e0c0be11d..d02622471 100644 --- a/src/main/java/org/springframework/data/util/Lazy.java +++ b/src/main/java/org/springframework/data/util/Lazy.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,18 +19,22 @@ import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; import java.util.Optional; +import java.util.function.Function; import java.util.function.Supplier; +import org.springframework.util.Assert; + /** * Simple value type to delay the creation of an object using a {@link Supplier} returning the produced object for - * subsequent lookups. + * subsequent lookups. Note, that no concurrency control is applied during the lookup of {@link #get()}, which means in + * concurrent access scenarios, the provided {@link Supplier} can be called multiple times. * * @author Oliver Gierke * @since 2.0 */ @RequiredArgsConstructor @EqualsAndHashCode -public class Lazy { +public class Lazy implements Supplier { private final Supplier supplier; private Optional value; @@ -60,4 +64,30 @@ public class Lazy { return value.orElse(null); } + + /** + * Creates a new {@link Lazy} with the given {@link Function} lazily applied to the current one. + * + * @param function must not be {@literal null}. + * @return + */ + public Lazy map(Function function) { + + Assert.notNull(function, "Function must not be null!"); + + return Lazy.of(() -> function.apply(get())); + } + + /** + * Creates a new {@link Lazy} with the given {@link Function} lazily applied to the current one. + * + * @param function must not be {@literal null}. + * @return + */ + public Lazy flatMap(Function> function) { + + Assert.notNull(function, "Function must not be null!"); + + return Lazy.of(() -> function.apply(get()).get()); + } }