4 ms·
These are called value types, and there isn’t really a problem with them if you start from scratch, but it is very far from trivial to introduce it in a backwar
by kaba0 4y ago
These are called value types, and there isn’t really a problem with them if you start from scratch, but it is very far from trivial to introduce it in a backwards compatible way plus solve it with generics in mind etc.
The current plan for Java is to divide the objects into 3 buckets, one being the current ones, they are distinct from the others in having identity.
The second group looses their identity, but they will retain their nullability. A great example for that would be the java.time package with e.g. LocalDate. Here two instance with the same fields will be semantically equal and replaceable, but there is no meaningful zero value as there is with numbers. If they would auto-initialize to 1970 that would probably cause some serious, hard to debug bugs later on. So they retain their nullability and they are tear-free. At initialization time they will only get visible in a state that is meaningful.
The last group will be similar to current primitives. They have a designated zero value, and seeing them in a consistent state is not guaranteed (in java, changing an int value even under race conditions is free from introducing values out of thin air, that is only values can appear that were actually set from any thread). In case of a complex number that you are about to change in two steps, another thread is free to observe it in an inconsistent state.
I really like this plan, and this way of thinking of object semantics actually helped me in other PLs as well. Do note that they don’t give any semantics on where the objects get stored, this is up to the VM implementation. In practice what it allows for is copying/flattening/stack-allocation of the second bucket, possibly with some clever encoding of null values a la Rust’s optionals. And the third group will allow for implementing custom numerics with basically no overhead.