I have a Java method. For the sake of being a public forum, I’m going to say that my method is called foo
Bar foo(Boolean flag)
{
flag = true;
return new Bar();
}
I get a warning by setting flag. Unfortunately, I have not found a way to suppress such a warning. Is there a “right” way of doing this? Now I know there are some who will say to simply not use an out parameter. Trust me when I say that I have a good reason for doing it this way. If there’s no way around the warning without doing something crazy, I suppose that’s fine. I just don’t like checking in code with warnings.
You’re getting a warning because your assignment is doing nothing useful. You shouldn’t check this code in because it doesn’t do what you think it does. For example:
Your code is setting the value of the
flagparameter, which won’t change anything about the value which is passed in. Java strictly uses pass-by-value, including when it’s passing reference (which it’s doing here).If
Booleanwere mutable you could write:and change the contents of the object that
xreferred to in the first snippet of code – but all the wrapper types in Java are immutable.Now it’s not really clear what your higher level purpose is, but basically it’s not going to be accomplished by the code you’ve given – so heed the warning, and change your approach.