Skip to content

talsma-ict/lazy4j

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CI build Coverage Status Maven Version JavaDoc

Lazy4J

A generic Lazy class in java

What is it?

A lazy function that is evaluated only when it is first needed, remembering the result so it does not get called again.

Technically, Lazy is a wrapper for standard Java Supplier functions.

Why?

We feel this ought to be provided out of the box and should have been when lambda's were introduced, back in Java 8.

Fortunately, it's not very difficult to create, so that's what we did.

Example

A small example of how this class can be used:

public class Example {
    // Method reference to Expensive.create() only when needed and remember the result.
    private final Lazy<Expensive> lazyMethod = Lazy.lazy(Expensive::new);

    // Lambda called only once when needed for the first time.
    private final Lazy<Expensive> lazyLambda = Lazy.lazy(() -> new Expensive());
}

This declares a lazy variable without calling the expensive supplier yet.
Only when get() is called for the first time, the new Expensive() constructor is called.
All subsequent invocations will return the same instance of Expensive.

Lazy provides the following methods:

  • isAvailable returning whether the lazy value is already available.
  • map applies a function on the lazy result.
  • flatMap applies a function that itself returns a supplier.
  • ifAvailable runs a function only if the lazy value is already available.

Please refer to the Lazy class documentation for full descriptions.

Getting the class

Add the following dependency to your project or download it directly from github:

Maven

<dependency>
    <groupId>nl.talsmasoftware</groupId>
    <artifactId>lazy4j</artifactId>
    <version>[see maven badge]</version>
</dependency>

Gradle

compile 'nl.talsmasoftware:lazy4j:[see maven-central badge]'

Scala

libraryDependencies += "nl.talsmasoftware" % "lazy4j" % "[see maven-central badge]"

License

Apache 2.0 license