Hi, as a .NET/C# coder I found the issue that there is not Action<T> and Func<T, TResult> equivalents in Java environment. I am self-study this to prepare myself for the OCA certification, and I had the idea that I could use lambda expression and implement simple equivalents of C# delegates in Java 8. Below you can find implementation with test cases. I found that the code can be straightforward because lambda expressions work as anonymous methods in C#. Moreover, use T as an internal class of method. You can have an entity available inside the lambda and outside, too, so you can extend the scope of parameters thanks to using an internal class or any scope entity class. I hope you like this simple example. Thanks for reading!
interface Action<T> { public void invoke(T arg); } class ActionImpl<T> implements Action<T> { Action<T> action; public ActionImpl(Action<T> action) { this.action = action; } @Override public void invoke(T arg) { this.action.invoke(arg); } } interface Func<T, TResult> { public TResult invoke(T arg); } class FuncImpl<T, TResult> implements Func<T, TResult> { Func<T, TResult> function; public FuncImpl(Func<T, TResult> function) { this.function = function; } @Override public TResult invoke(T arg) { return this.function.invoke(arg); } } class LambdasTests { public void myMethod(Integer x) { System.out.println(x); } public void test01() { Action<Integer> delegateLike = new ActionImpl<Integer> (x -> myMethod(x)); delegateLike.invoke(1024); } public void test02() { Action<String> delegateLike = new ActionImpl<String> (s -> { System.out.println(s);} ); delegateLike.invoke("Boo!"); } public void test03() { class Entity { public String s; public int x; } Entity entity = new Entity(); entity.s = "Bo3!"; entity.x = 0; Action<Entity> delegateLike = new ActionImpl<Entity> (ent -> { System.out.println(ent.s); ent.x += 1234; } ); delegateLike.invoke(entity); System.out.println(entity.x); delegateLike.invoke(entity); System.out.println(entity.x); } public Integer increment(Integer x) { return x + 1; } public void test04() { Func<Integer, Integer> delegateLike = new FuncImpl<Integer, Integer> (x -> increment(x)); System.out.println(delegateLike.invoke(1023)); } } public class LambdasTestsInvoker { public static void main(String[] args) { LambdasTests lt = new LambdasTests(); lt.test01(); lt.test02(); lt.test03(); lt.test04(); } }
p ;).
Hi! Thanks for the code! I have a question, Action per se does not return any value, am I right? How can the value be access from another place? It is beacuse I am struggling with c#’s event actions variable, so I want to look for an equivalent of a segment of code that says ‘event action’ += method, meaning it subscribes to the event and asks for the current value the action has?