Why is this an issue?

It is common for code to have unnecessary variable assignments. Unnecessary variable assignments make code harder to read and maintain. By avoiding these redundant assignments, your code will be more efficient and understandable.

How to fix it

Code examples

Noncompliant code example

In this example, i is declared and assigned a value of 0. The value of i is immediately replaced with 1 and then again with 2.

var i = 0 // Noncompliant, useless initializer, will be overwritten in the next line
i = 1 // Noncompliant, the value will be overwritten in the next line
i = 2

Compliant solution

The code can be simplified by assigning i the value of 2 when it is declared.

var i = 2

Noncompliant code example

To expand on the previous example, we have added a read-only variable j, which is assigned the value of i`. Since `i is the post-increment operator, the value of i is first used for the assignment, and then incremented by 1. Thus the value of j is 2.

var i = 2
...
val j = i++ // Noncompliant, result of 'i++' increment is never used

println(j)

Compliant solution

By removing the redundant post-increment operator you avoid introducing unnecessary operations. As a result, your code becomes easier to read.

var i = 2
...
val j = 2

println(j)

Resources

Documentation