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?
You would have to cast the lambda to a functional interface first:
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
orvolatile
.