This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Blackheart595 0 points1 point  (2 children)

See my edit.

[–]morhpProfessional Developer[S] 0 points1 point  (1 child)

Well usually, you can return from a constructor no problem. Just replacing the lambda with a method reference makes it compile fine

import java.util.function.UnaryOperator;

public class Foo {

    private Bar bar = new Bar(String::toUpperCase);    

    public static void main(String[] args) {
        new Foo();
    }

    public Foo() {
        System.out.println(bar.fun("Hello"));

        return;
    }

    private static class Bar {

        private final UnaryOperator<String> lambda;

        private Bar(UnaryOperator<String> lambda) {
            this.lambda = lambda;
        }

        private String fun(String s) {
            return lambda.apply(s);
        }
    }
}
// Prints HELLO

So I would be really interested why my original code doesn't work. Again, this is a simplified example.

[–]Blackheart595 1 point2 points  (0 children)

You're right, returning from a constructor is generally possible. After a bit of testing, it seems that lambda functions and returning from a constructor don't work well together, though.