Assign result of Java lambda to field [duplicate]

2019-08-16 14:06发布

问题:

This question already has an answer here:

  • How to initialize field using lambda 1 answer

I want to use a lambda in Java to configure a field on an object at creation time. This means that I have to invoke the lambda inline, but I have seen no examples that run a lambda before first assigning it to something. Specifically I want to do something like this:

private JTextField tfInput = () -> { JTextField tf = JTextField(""); tf.setEditable(false); return tf; }();

Is this possible in Java?

回答1:

You would have to cast the lambda to a functional interface first:

private JTextField tfInput = (Supplier<JTextField>)(() -> {
    JTextField tf = new JTextField("");
    tf.setEditable(false);
    return tf;
}).get();

But I'm not sure why you'd opt for this instead of declaring a simple method, or initializing from the constructor or an initializer block. Also, note that if you're trying to make sure the field is only visible after it's initialized, you may need to make it final or volatile.



标签: java lambda