2

How can I teach IntelliJ to not initialize Collections with null values? (e.g. the following code will make IntelliJ mark my result variable, saying that it needs to be initialized, and that's fine)

But when I use ALT+Enter on it to fix this, it will always initialize with null, although it would be better to initialize with an empty list.

public class A {
  List<B> method(){
    List<B> result;

    try {
      result = this.getResults();
    } catch(Exception e){
      // nothing
    }

    return result;
  }
}

Is there a way to change this default behaviour?

Blake Yarbrough
  • 2,286
  • 1
  • 20
  • 36
Unknown Id
  • 460
  • 3
  • 12

2 Answers2

1

The closest you can get is to Create a Live Template.

  1. In the Settings dialog, open the Live Templates page, and expand the template group where you want to create a new template.

  2. Click the +. A new template item is added to the group and the focus moves to the Template Text area.

  3. Specify the new template abbreviation, type the template body, define the variables and the template group, configure the options, as described in the template modification procedure.

  4. Click OK when ready.

Then you can insert the template (e.g. new ArrayList<$LISTTYPE$>()) using whatever hotkey you defined in your template definition.

  1. Place the caret at the desired position, where the new construct should be added.

  2. Do one of the following

    • On the main menu, choose Code | Insert Live Template.
    • Press Ctrl+J.
    • Type some initial letters of the template abbreviation to get the matching abbreviations in the suggestion list. Note that the suggestion list may contain same abbreviations for different templates.
  3. From the suggestion list, select the desired template. While the suggestion list is displayed, it is possible to view Quick Documentation for the items at caret, by pressing Ctrl+Q.

  4. Press the template invocation key (this may be Space, Tab or Enter, depending on the template definition). The new code construct is inserted in the specified position.

  5. If the selected template is parametrized and requires user input, the editor enters the template editing mode and displays the first input field highlighted with the red frame. Type your value in this frame and press Enter or Tab to complete input and pass to the next input field. After completing the last input field, the caret moves to the end of the construct, and the editor returns to the regular mode of operation.

Blake Yarbrough
  • 2,286
  • 1
  • 20
  • 36
0

It's probably better to code it like

    try {
        result = this.getResults();
    } catch(Exception e){
        result = Collections.emptyList();
    }

making sure the variable is assigned in all possible code paths.

ZhongYu
  • 19,446
  • 5
  • 33
  • 61