Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a reference of `System.out.println` to a variable?

Tags:

java

I want to assign the reference to variable p:

Function<?, Void> p = System.out::println; // [1]

so that I can use it like:

p("Hello world"); // I wish `p` to behave exactly same as `System.out.println`

Expression [1] produce a compilation error, how to resolve it?

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

The type of println(Object) from the type PrintStream is void, this is incompatible with the descriptor's return type: Void

If change Void to void the error becomes:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error, insert "Dimensions" to complete ReferenceType

like image 548
djy Avatar asked Dec 10 '22 04:12

djy


2 Answers

Unfortunately, you can't put all the overloads of System.out.println into one variable, which is what you seem to be trying to do here. Also, you should use the functional interface Consumer instead of Function.

You can store the most generic System.out.println overload, which is the one that takes an Object, in a Consumer<Object>:

Consumer<Object> println = System.out::println;
println.accept("Hello World!");

Or if you just want the overload that accepts a String,

Consumer<String> println = System.out::println;

Note that it is impossible to achieve the syntax you want (print("Hello World") directly) with functional interfaces.

Also note that if you pass a char[] to println.accept, it will not behave the same way as System.out.println(char[]). If this bothers you, you can instead use a static import:

import static java.lang.System.out;

And then you can do:

out.println(...);
like image 133
Sweeper Avatar answered Jan 12 '23 14:01

Sweeper


PrintStream out = System.out;
out.println("helo world");

Why don't just save System.out into variable and then use it?

Another solution, to not loose compilation time check for println(), is use String.format() function. You can add it to the variable:

BiConsumer<String, Object> println = (format, args) -> System.out.println(String.format(format, args));
println.accept("hello world", null);
like image 28
oleg.cherednik Avatar answered Jan 12 '23 15:01

oleg.cherednik