netbeans icon indicating copy to clipboard operation
netbeans copied to clipboard

Record compact constructor parameters are considered unused

Open sviperll opened this issue 3 years ago • 1 comments

Apache NetBeans version

Apache NetBeans 14

What happened

Defining compact constructor almost always results in "unused local variable" warning, because NetBeans is unaware of implicit field assignments that happen after compact constructor code is executed.

In an example:

record MyRecord(List<String> list, int[] ints) {
    MyRecord {
        list = List.copyOf(list); // WARNING: unused local variable
        ints = Arrays.copyOf(ints); // WARNING: unused local variable
    }
}

I expect there to be no warnings, because above code is totally legitimate and even more recommended way to use compact constructor.

How to reproduce

Define any record with compact constructor that assigns to constructor parameters.

Did this work correctly in an earlier version?

No

Operating System

Fedora 34

JDK

JDK 18

Apache NetBeans packaging

Apache NetBeans binary zip

Anything else

No response

Are you willing to submit a pull request?

No

Code of Conduct

Yes

sviperll avatar Jun 21 '22 10:06 sviperll

ctrl+r rename refactoring is also not renaming the record field, this might help finding the issue. Seems like the IDE thinks those are two separate fields.

mbien avatar Jul 16 '22 16:07 mbien

I'm seeing this still happening on NB 19.

dstutz avatar Oct 16 '23 14:10 dstutz

Another example for minimal value validation (NB version 19):

	public record WaitOptions(int timeoutSeconds, boolean expectSuccess) {
		public WaitOptions {
			if (timeoutSeconds <= 0) {
				timeoutSeconds = 5; // NBv19 Warning: Unused Assignment
			}
		}
	}

The assignment is used though, because: var opt = new WaitOptions(0, true) results in opt.timeoutSeconds == 5.

Eccenux avatar Apr 04 '24 16:04 Eccenux

@Eccenux is this reproducible in NB21?

@mbien is this meant to still be open?

neilcsmith-net avatar Apr 04 '24 17:04 neilcsmith-net

@neilcsmith-net yes, NB thinks record components and the constructor parameters are two different fields, this is the cause for several issues, also during refactoring. You can also see this while highlighting is active (cursor over identifier).

mbien avatar Apr 04 '24 17:04 mbien

@neilcsmith-net wait, I was wrong. This was indeed fixed in NB 20, sorry!

(although NB still thinks components and constructor parameters are two different things - renaming/highlighting does not work properly)

mbien avatar Apr 26 '24 10:04 mbien