How come... part 1: importing statically

Remi Forax forax at univ-mlv.fr
Sun Jan 5 06:07:51 PST 2014


On 01/04/2014 03:21 PM, Timo Kinnunen wrote:
> Hi,
>
>
> 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:
>
>
> s1.forEach(System.out::println);
>
>
> 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?

The rational is don't abuse of static import :)

basically what you want is something like
   s2.forEach(::println)

which has been rejected by the EG as too ambiguous,
because you don't know if it's a shortcut for this::println, 
CurrentClass::println
or as you want with System.out::println, println being an import static.

Another solution is to avoid to allow instance in front of ::,
in that case, ::println becomes not too ambiguous but we loose an 
important feature, currying.

So there is good reason for horses to not have wings,
because you have to choose between wings and horse armor.

cheers,
Rémi



More information about the lambda-dev mailing list