Queries regarding value classes

Quân Anh Mai anhmdq at gmail.com
Sat Mar 19 09:16:42 UTC 2022


>  Maybe I'm thinking a little too much in the C++ model of classes?

Yes, you are. In C++, when you do an assignment `a = b`, the copy
assignment operator method is called, often copies the content of the
second operand into the first one, the `=` here is not anything special but
syntactic sugar for a method call. In Java on the other hand, when you do
`a = b`, then `a` and `b` now are the same object, the fact that they are
implemented as a reference or not is irrelevant, the language semantics
does not really care about that. As they are now the same object, every
change to the object through `a` must be observable through `b`, which
means that if you do `a.x = 3`, now `b.x` should also give the answer `3`
(there is the memory model also but for simplicity let's only consider
single-threaded environment). As a result, the fact that value objects are
immutable allows the compiler to copy them without worrying about the
circumstances I present above. Again, copying or not is the choice of the
compiler, it may choose to do so, it may not. From the language point of
view, irrespective of which choice the compiler made, `a` and `b` must
still be the same object and indistinguishable from each other until you
assign to one of them another object.

So in short, you are messing the causes and consequences around, the
immutability of the value objects allows the compiler to copy them around
without considering where did the object originate from, and if you want
the objects to be mutable, then the compiler cannot copy them anymore.

Regards,
Quan Anh

On Sat, 19 Mar 2022 at 16:53, Julian Waters <tanksherman27 at gmail.com> wrote:

> My naive understanding is that the reference to the original object that
> was created would still change only it, while the new inlined object would
> then be accessed by another reference, but I am not sure if this is
> correct.
>
> best regards,
> Julian
>
> On Fri, Mar 18, 2022 at 9:37 PM Pedro Lamarão <
> pedro.lamarao at prodist.com.br>
> wrote:
>
> > Em sex., 18 de mar. de 2022 às 09:03, Julian Waters <
> > tanksherman27 at gmail.com> escreveu:
> >
> >
> >> I suspect the misunderstanding in the thread is caused by my
> >> confusion of what value classes actually *are*, I'm still having a hard
> >> time figuring out how a reference object cannot be mutated
> >>
> >
> > This is my understanding as a layman, not a Valhalla expert.
> > Suppose you create some value class object.
> > It lives in the heap.
> > Then you pass it around.
> > Then an opportunity arises and this object is inlined in some other
> object.
> > You still have a reference to the object you created initially.
> > You change a field on that object through that reference.
> > What do you expect must happen with the inlined version?
> >
> > --
> > Pedro Lamarão
> >
>



More information about the valhalla-dev mailing list