Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lint Warning: Variable is already assigned to this value

I get the lint warning Variable is already assigned to this value when doing something like the following

String[] sa =getStringArray();
sa = modifyArrayandMakeAwesomer(sa);  //get the warning here

Seems to be a new warning for me. Perhaps my lint settings have changed. The code works as expected without any errors. Is it bad practice? Should I declare a second string array?

like image 365
seekingStillness Avatar asked Jan 21 '19 17:01

seekingStillness


1 Answers

Because modifyArrayandMakeAwesomer(sa) is modifying your data using its reference,

class Person {
   String name;
}

// this method just return the string value after making it uppercase,
public static Person modifyReference(Person p)
{
  p.name = "Gaurav";
  return p; // we don't need to return this from here since we are modifying directly to the reference.
}

public static int main(String[] args)
{
  Person p = new Person();
  p.name = "Max";
  System.out.println(p.name);
  modifyReference(p); // this is what you should do,
  p = modifyReference(p); // this is useless, since you have passed the reference of Person class 
  System.out.println(p.name);
}

like image 61
GouravGupta Avatar answered Sep 27 '22 16:09

GouravGupta