Iterating over an Array. Example of Applying Parameterized Live Templates
As an example of applying a parameterized template, let us create a construct that iterates over an array.
To iterate over an array
- Open the desired class for editing.
- Type the
itar
abbreviation: - Press the template invocation key. The abbreviation expands into a code construct, with the suggested values for the template's variables already inserted:
- The Editor is now in its special template editing mode. The cue is the red border around the index
variable, which is the first input position in this template.
IntelliJ IDEA automatically suggests
i
as the value for the index variable. If you want to change the suggested name, type a new one. All references to the variable within the expanded template will be automatically changed as you type the new name.In figure below,
i
is changed toidx
: - Press Tab or Enter to move to the next input position
defined by the template:
As you can see on the image above, IntelliJ IDEA automatically detects all array elements in the scope, and suggests selecting the correct one. If there is only one array element in the scope, IntelliJ IDEA inserts its name automatically without displaying a pop-up list.
- IntelliJ IDEA detects whether the type of the array elements changes. It automatically updates the type of the variable that holds the current array element, and suggests a list of reasonable names for it:
- Press Tab or Enter to apply the selected/specified variant. This will move you to the next input position which in our case is the END position of the template: