public interface Lazy<T>
Lazy
computes its value on
the first call to get()
and remembers that same value for all
subsequent calls to get()
.
null
is not a supported value. Implementations of Lazy
are expected to throw NullPointerException
if the computed value is
null
.
@Module
public class CounterModule {
int next = 100;
@Provides Integer provideInteger() {
System.out.println("computing...");
return next++;
}
}
public class DirectCounter {
@Inject Integer value;
public void print() {
System.out.println("printing...");
System.out.println(value);
System.out.println(value);
System.out.println(value);
}
}
Injecting a DirectCounter
and invoking print()
reveals that
the value is computed before it is required:
computing...
printing...
100
100
100
Provider.get()
3 times and prints each result:
public class ProviderCounter {
@Inject Provider provider;
public void print() {
System.out.println("printing...");
System.out.println(provider.get());
System.out.println(provider.get());
System.out.println(provider.get());
}
}
Injecting a ProviderCounter
and invoking print()
shows that
a new value is computed each time Provider.get()
is used:
printing...
computing...
100
computing...
101
computing...
102
Lazy
for the integer. Like the provider above,
it calls Lazy.get()
3 times and prints each result:
public static class LazyCounter {
@Inject Lazy lazy;
public void print() {
System.out.println("printing...");
System.out.println(lazy.get());
System.out.println(lazy.get());
System.out.println(lazy.get());
}
}
Injecting a LazyCounter
and invoking print()
shows that a new
value is computed immediately before it is needed. The same value is returned
for all subsequent uses:
printing...
computing...
100
100
100
Lazy
is independent, and remembers its value
in isolation of other Lazy
instances. In this example, two LazyCounter
objects are created and print()
is called on each:
public void run() {
ObjectGraph graph = ObjectGraph.create(new CounterModule());
LazyCounter counter1 = graph.get(LazyCounter.class);
counter1.print();
LazyCounter counter2 = graph.get(LazyCounter.class);
counter2.print();
}
The program's output demonstrates that each Lazy
works independently:
printing...
computing...
100
100
100
printing...
computing...
101
101
101
Use @Singleton to share one instance
among all clients, and Lazy
for lazy computation in a single client.T get()
Lazy
instance will return the same result.NullPointerException
- if the computed value is null
.Copyright © 2015 Google, Inc.. All rights reserved.