Assign result of Java lambda to field [duplicate]

2019-08-16 14:42发布

This question already has an answer here:

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?

标签: java lambda
1条回答
Explosion°爆炸
2楼-- · 2019-08-16 15:04

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.

查看更多
登录 后发表回答