Assume we have a simple class:
public with sharing class SomeClass {
public String property {
get;
set;
} {
property = 'Default Property Value';
}
public final String finalProperty {
get;
set { finalProperty = value; }
} {
finalProperty = 'Default Final Property Value';
}
public final String finalAutoProperty {
get;
set;
} {
finalAutoProperty = 'Default Final AutoProperty Value';
}
}
Anonymous Execution
SomeClass instance = new SomeClass();
instance.property = 'New Property Value';
instance.finalProperty = 'New Final Property Value'; // Works
instance.finalAutoProperty = 'New Final AutoProperty Value'; // Fails with
System.FinalException: Final variable has already been initialized
Class.SomeClass.__sfdc_finalAutoProperty
However, as @sfdcfox сorrectly noticed, neither
instance.finalProperty = 'New Final Property Value';
nor instance.finalAutoProperty = 'New Final AutoProperty Value';
reassignments
couldn't be compiled within another method giving:
Final members can only be assigned in their declaration, init blocks, or constructors
This behavior gives me questions because:
- final keyword ApexDocs doesn't mention that the
final
keyword affects the behavior of properties and the Apex Properties page doesn't mention thefinal
keyword. But thefinal
keyword does affect apex properties. - Is it undocumented expected behavior or a new bug?
- Why it is possible to reassign the property value within anonymous execution via default setter, but not via auto-generated setter?