I am trying to understand lambdas in Java 8. I have this very simple example using a functional interface.
This is not a working example and I understand that I can directly call method1 and method2 rather than using getValue() and Supplier, but, I wanted to know if there are any issues with calling method1 and method2 using supplier.get().
public <T> T mytest(SomeObject var) { //extract values from someobject if(somecondition) { getValue(() -> method2(obj5instance, obj6instance)); } else { getValue(() -> method1("somestr", obj1instance, obj2instance, obj3instance)); } } private String method1(String s1, Obj1 s2, Obj2 s3, Obj3 s4){ //network call here to compute return value return "computedmethod1"; } private String method2(Obj5 s2, Obj6 s3){ //network call here to compute return value return "computedmethod2"; } public <T> T getValue(Supplier<T> supplier){ //this will call method1 or method2 //wrap the return value from supplier.get and return return supplier.get(); } Update based on Andrew's comment.
That makes a lot of sense, thanks. I am having difficult wrapping my head around the concept of supplier.
C1.java
public C3 m1(Obj obj){ Supplier<String> mysupplier = () -> foo(arg1, arg2, arg3); //foo is an expensive call return someFn(mysupplier); } How does supplier work internally? When the supplier is created, does it keep a reference to foo() and the arguments passed to foo?
public C3 someFn(Supplier<String> supplier){ //this returns an instance of C3 that has a method lazyCall() which runs supplier.get() } C2.java
C3 c3 = c1.m1(obj); If and when c3.lazyCall() is called, it runs the supplier.get() and foo is run. Is this a valid use of supplier?
mytesthas no return statement. it can't compile.