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

  • A+
Category:Languages

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

 


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(...); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: