Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling System.out.println() through a lambda expression

In C# I can write the following code:

public static Action<object> WL = x => Console.WriteLine(x);

... and then every time that I want to write something out to the console I just call:

WL("Some output");

What would be the equivalent code using Java 8 lambda expressions? I tried the following and it does not work:

static void WL = (String s) -> { System.out.println(s); }
like image 551
λ Jonas Gorauskas Avatar asked May 08 '14 23:05

λ Jonas Gorauskas


1 Answers

Your current attempt doesn't work because you're trying to declare a variable of type void - the equivalent would fail in C# too. You need to declare a variable of a suitable functional interface, just like you use a delegate type in C#.

You can do it with a lambda expression, but it would be cleaner (IMO) to use a method reference:

import java.util.function.Consumer;

public class Test {
    public static void main(String[] args) {
        Consumer<Object> c1 = x -> System.out.println(x);
        Consumer<Object> c2 = System.out::println;

        c1.accept("Print via lambda");
        c2.accept("Print via method reference");
    }
}

Here the Consumer<T> interface is broadly equivalent to the Action<T> delegate in .NET.

Similarly you can use a method group conversion in C# rather than a lambda expression:

public static Action<object> WL = Console.WriteLine;
like image 111
Jon Skeet Avatar answered Sep 24 '22 13:09

Jon Skeet