checkstyle / checkstyle/checkstyle
VarFinalLocalVariable: Enforce var with final local variables
- Dominant language
- Java
- Stars
- 9.6k
- Forks
- 4.2k
- Avg merge
- 22h 23m
- Merged PRs (30d)
- 232
Description
The var reserved type was introduced in Java 10. Type inference is used in var keyword in which it detects automatically the datatype of a variable based on the surrounding context.
I would like to create a checkstyle check that enforces that all final local variables use the `var` reserved type. This is to avoid duplication of type references in statements. This code style is used in some projects, but it is currently difficult to enforce because there is no specific checkstyle rule for this.
**Proposed configuration**
```xml
```
**Incorrect style**
For example, the following code would fail the `VarFinalLocalVariable` check:
```java
public int square() {
final int a = 5;
return a * a;
}
```
The following warning could then be logged by checkstyle for example:
`Final variable 'a' should be created via 'var' keyword to avoid duplication of type reference in statement.`
**Correct style**
This would be the correct style which would not break the `VarFinalLocalVariable` rule.
```java
public int square() {
final var a = 5;
return a * a;
}
```
**Current approach**
At the moment you can enforce final local variables to be declared with `var` by using the following `MatchXpath` rule:
```
```
Contributor guide
Assessment
This issue has not been assessed yet.