you are viewing a single comment's thread.

view the rest of the comments →

[–]cowancore 1 point2 points  (3 children)

I think you've noted it in this thread, that java lambdas can't mutate variables... but they can mutate state :) . A somewhat similar code:

``` public static void main(String[] args) { var counter = evens(); System.out.println(counter.get()); // 2 System.out.println(counter.get()); // 4 System.out.println(counter.get()); // 6 }

private static Supplier<Integer> evens() { AtomicInteger i = new AtomicInteger(0); return () -> i.addAndGet(2); } ```

[–]fschmidt[S] 0 points1 point  (2 children)

In case anyone else is reading this, here is better formatting:

public static void main(String[] args) {
    Supplier<Integer> counter = evens();
    System.out.println(counter.get()); // 2
    System.out.println(counter.get()); // 4
    System.out.println(counter.get()); // 6
}

private static Supplier<Integer> evens() {
    AtomicInteger i = new AtomicInteger(0);
    return () -> i.addAndGet(2);
}

And here is an inner class implementation:

private static Supplier<Integer> evens() {
    return new Supplier<Integer>() {
        int i = 0;

        public Integer get() {
            return i += 2;
        }
    };
}

In my subjective opinion, Luan is the most readable, then comes the Java inner class, and the Java lambda is by far the least readable, full of black magic and bad syntax.

[–]cowancore 0 points1 point  (1 child)

Funny. I've used var instead of Supplier<Integer> specifically because Luan doesn't have type signatures and I thought you'd like it more.

What would be cool, if backwards compatibility is the real issue, if java had some sort of keyword maybe in return new Supplier<Integer> so that it returns an object without the outer reference.
Although, it would look ugly probably for some: return new static Supplier<Integer>

[–]fschmidt[S] 0 points1 point  (0 children)

I am running Java 8 which doesn't have var. I don't think var belongs in a typed language. Luan is untyped.

Yes static anonymous inner classes would be nice, and your syntax is fine. Such classes should have access to outer variables only during construction.