Re: How come... part 1: importing statically
timo.kinnunen at gmail.com
Sat Jan 4 06:21:00 PST 2014
Don’t worry, I’ll only post things that deal with lambdas that have me scratching my head to this list. I have a feeling that there might be more, but let’s hope there isn’t :)
Now, on to this issue.
Picking my words deliberately and carefully in order to make my point, import static allows me to reference a method as if it had been declared in my class:
import static java.lang.String.valueOf;
[. . .]
Stream<String> s1 = IntStream.of(1, 2).mapToObj((int i) -> valueOf(i));
Lambdas are - still, hopefully - intended to be less instances of anonymous classes and more like anonymous code. When passed around they manifest as pointers to code, or the internal functions containing the code, references to internal methods if you will. The above Stream can be declared also like this:
Stream<String> s2 = IntStream.of(1, 2).mapToObj(String::valueOf);
This pointer-to-code nature makes it natural to convert from a method reference to a lambda, like above. And this nature is so strong that converting from a reference to some object’s instance method is just as easy as if it was a static method, in this case a PrintStream method of an object in the static field System.out, like you mentioned:
As before, a strong pointer-to-code similarity between lambdas and methods of both instance and static kinds let’s us neatly come back full circle and also write the above like. . . OK, so how come this is an error suddenly?
import static java.lang.System.out.println;
[. . .]
s2.forEach((String s) -> println(s));
Where is the Zen in this?
Have a nice day,
Sent from Windows Mail
From: Richard Warburton
Sent: Saturday, January 4, 2014 16:00
To: Timo Kinnunen
Cc: lambda-dev at openjdk.java.net
but I can’t write:
import static java.lang.System.out::printf;
. . .
What’s up with that?
import static let's you import static fields or methods with an abbreviated syntax. printf isn't a static field or method - its an instance method of the PrintStream class. On the other hand "out" is a static field of the System class, so you can do:
import static java.lang.System.out;
What you asking for is a situation where "import static" imports things that aren't static. This would almost inevitably lead to an alternative "How come ..." question!
(This is part 1 in my How come... series, more parts as they come.)
I will observe that this question didn't really have anything to do with lambda expressions and stack overflow deals very well with general Java questions.
More information about the lambda-dev