Breaking the silo #1

Lambdas

Java 

> Lambdas were adopted in Java 8

> Defined as an expression of an instance of a single-method anonymous class

C#

> Anonymous methods were introduced in C# 2.0

> Lambda expression in C# 3.0

> Defined as a function that can be passed as an argument or returned as the value of function calls

(Java 8)

(C# 6)

Java 

C#

param -> Do.somethingWith(param)
p -> {
    return Something.For(p);
}
param => Do.somethingWith(param)
(param) => { 
                Do.OneThingWith(param);
                Do.AnotherThing();
            }
() => Do.something()
(input parameters) => Expression;
(p1, p2) -> {
    Do.SomethingWith(p1);
    return Something.For(p2);
}
listOfStuff.Select(x => doFilter(x));
Apply method group transformation :
listOfStuff.Select(doFilter);
listOfStuff.stream().map(x => doMap(x));
Apply method reference transformation :
listOfStuff.stream().map(this::doMap);
public void RunParamAction(Integer input1,
                         String input2,
                         BiConsumer<Integer, String> callback) {
    Do.something();
    callback.accept(input1, input2);
}

private void CallLambdaAction() {
    RunParamAction(1, "Hello", (param1, param2) -> System.out.println(param1 + param2));
}
public void RunParamAction(KeyValuePair<int, string> inputs, Action<int, string> callback)
{
    Do.Something();
    callback(inputs.Key, inputs.Value);
}

private void CallLambdaAction()
{
    RunParamAction(new KeyValuePair<int, string>(1, "Hello"), (param1, param2) =>
                                                              Console.WriteLine(param2 + param1));
}

Java

C#

public String FromParamFunction(Integer input,
                              Function<Integer, String> callback) {
    Do.SomethingElse();
    return callback.apply(input);
}

private void CallLambdaFunction() {
    String result = FromParamFunction(1, param -> param > 1 ? "HI!" : "Bye!");
}
public string FromParamFunction(int input, Func<int, string> callback)
{
    Do.SomethingElse();
    return callback(input);
}

private void CallLambdaFunction()
{
    var result = FromParamFunction(1, (param) => param > 1 ? "HI!" : "Bye!");
}

Java

C#

Breaking the Java C# Silo #1

By hkoundi

Breaking the Java C# Silo #1

  • 771