IntelliJ IDEA 2017.3 Help

Extract Functional Variable

IntelliJ IDEA lets you extract a functional type variable.

This refactoring creates a functional expression for Java 1.8 and later versions, and an anonymous class for older versions of Java.

Example

BeforeAfter
import java.util.List; public class PrintAction implements Runnable { private List<String> data; public PrintAction(List<String> data) { this.data = data; } public void run() { System.out.println("Data: " + data.toString()); } }
import java.util.List; import java.util.function.Function; public class PrintAction implements Runnable { private List<String> data; public PrintAction(List<String> data) { this.data = data; } public void run() { Function<List<String>, String> presenter = (p) -> "Data: " + p.toString(); System.out.println(presenter.apply(data)); } }

Extracting a functional variable

  1. Select the code fragment, in this example, an argument of the println method.
    /help/img/idea/2017.3/argument_println.png
  2. In the main menu, select Refactor | Extract | Functional Variable.
    IntelliJ IDEA opens the Extract Functional Variable dialog.
    /help/img/idea/2017.3/extrct_funtional_var.png
  3. When the selected code depends on instance fields, like in the example, the Pass field as params checkbox will appear and you can pass a parameter in a place of fields.
    /help/img/idea/2017.3/extrct_funtional_var_parameter.png
    However, if for example, your selected code fragment depends on any local variable or a parameter
    /help/img/idea/2017.3/sample_string.png
    the corresponding entries would appear in the list.
    /help/img/idea/2017.3/local_variable_and_parameter.png
    When you deselect one of the parameters in the dialog, the corresponding local values will be used instead.
    /help/img/idea/2017.3/when_param_deselected.png
    Configure your options and click OK.
  4. Choose an applicable functional interface from the pop-up.
    /help/img/idea/2017.3/functional_interface.png
  5. If you want, change a name of the extracted variable if you don't want to use the name suggested in the list.
    /help/img/idea/2017.3/changing_variable_name.png

As a result, IntelliJ IDEA creates lambda that you can use further.

/help/img/idea/2017.3/composed_function.png
See also the functional parameter refactoring.

Last modified: 11 October 2017

See Also