Return to site

☕ JAVA TRICK: Compact Record Constructors

· java

You know how to use records to model data carriers and 

how to verify incoming data during construction,

but did you know💡 that you don't have to list the parameters of all record constructors?

A record's 𝒄𝒂𝒏𝒐𝒏𝒊𝒄𝒂𝒍 constructor has one argument per component

but in its 𝒄𝒐𝒎𝒑𝒂𝒄𝒕 form, you don't have to list them.

You can't assign fields, that happens in compiler-generated code after yours,

but you can reassign the parameters, which leads to the same result.

𝐖𝐈𝐓𝐇 𝐭𝐡𝐞 𝐂𝐨𝐦𝐩𝐚𝐜𝐭 𝐂𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫

𝐖𝐈𝐓𝐇𝐎𝐔𝐓 𝐭𝐡𝐞 𝐂𝐨𝐦𝐩𝐚𝐜𝐭 𝐂𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫