In the context of Java's Project Valhalla, how can I generically initialize a value type with its default value?
Initially, I thought that assigning null
to any value type would perform this initialization. However, the answers and comments to this question clearly show that null
is a reference, so it has nothing to do with value types (precisely due to the fact that value types are not references, but direct values instead).
E.g. if I have a Person
value type with StringValueType name
and DateValueType dateOfBirth
attributes (here dateOfBirth
would be a nested value type containing int year
, int month
and int day
attributes), how could I initialize my Person
value type in a generic way so that the values of its attributes are ""
for name
and (0, 0, 0)
(or the corresponding default value) for dateOfBirth
, respectively?
To make it more clear, if this were C, I would do:
memset(myPersonStructVariable, 0, sizeof(Person));
Or in modern C:
struct Person myPersonStructVariable = {0};
The value type equivalent of the
aconst_null
bytecode (i.e.null
, which would be the default for reference types), is thevdefault
bytecode. From the minimal value type spec:And 2.3.5:
And a quote from this presentation says:
So that would be similar to what you do in C with
memset(myStructVar, 0, size)
.There is currently no language support for value types, so we can not say if there will be something like a
null
literal that would return the default value of a value type (e.g.MyValueType x = default(MyValueType)
or something like that), but the byte code exists. The presentation also shows how you'd use method handles to invokevdefault
. Alternatively, you'd have to spin bytecode.Initializing fields to a user defined value (e.g.
""
forStrinValueType
) would probably just happen through calling a constructor (or a value type equivalent). But it really isn't clear at this point in time, so we can only speculate.Also, check out the latest draft for the valhalla vm prototype here: http://mail.openjdk.java.net/pipermail/valhalla-dev/2017-December/003631.html