Description
The struct proposal requires that all fields in a struct/data class be final. The motivations around this are primarily around representation: one of the problems that I am aiming to solve is that we have a demonstrated need for object representations that allow the compiler to freely do scalar replacement of aggregates/unboxing optimizations that do not preserve identity (I believe that our SIMD classes already do this, in mild violation of the specified behavior). A secondary motivation is around brevity: based on the user feedback we've received around data classes, by far the common case that people wish to support is immutable data. Specifying that all fields in a struct are immutable allows the briefed int x
field declaration form to be used instead of the more verbose final int x
form.
Is this the right choice?
On the semantic end, allowing mutable fields + unboxing is very questionable. Aliasing of mutable objects must be predictable: if the compiler is free to unbox and re-materialize a single mutable object, chaos ensues. There are three possible solutions I see to this:
- Say that any struct with a mutable field must preserve object identity (but fully immutable structs do not)
- Say that mutable fields in a struct must be represented via an additional indirection which preserves identity.
- Say that all structs must preserve identity
On the brevity end, I see (at least) three choices:
- Say that all fields in a struct are mutable by default and require final fields to be marked as usual in the primary constructor
- Say that all fields in a struct are immutable by default, but allow fields to be marked mutable with
var
(e.g.var int x
) - Say that fields declared in the primary constructor are immutable, but allow mutable by default fields to be declared in the body of the struct.