The fine Twitter util library has the following Java class, which is extended by a Scala class that reads the volatile field and updates it using AtomicReferenceFieldUpdater. Access must be at least private, i.e., must allow other.state.
Is the motivational claim in the comment true? How true? (“How” means in what way and to what degree.)
public class IVarField<A> {
/** This is needed because we cannot create a field like this in Scala. */
volatile State<A> state;
}
Something like the following works.
Making the field "private [this]" turns it into the desired field reference ("getfield").
Access from a different instance is through an accessor "state()" which, if made @inline, will happily loosen the access restriction to the field.
That also means that the updater (which happens to reside in the companion module) can also access it.
(Because the normal accessor for the var is not emitted for an object-private member, you can define your own, using parens. But you don’t need to use parens at the call site, other.state. Your uniform access principle dollars at work. Or Swiss francs.)
Also notice the totally hip usage of
`new`in backticks for a param name. Idon’teven know how to make the ticks show up in this markup. Because both params are the same type, one is likely to want to writecas(expect=prev, `new`=changed), so I might have usednextinstead, but if this markup supported a hipster thumbs-up, I’d give it right now. :+1: Did it work? Can anyone see my thumb? [I guess I saw that on github. Hubster, not hipster.]Showing that state() is really inlined:
Not only is it "OK to ask and answer your own questions",
https://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/
it’s infinitely more satisfying.
(More power to Daniel Sobral, Rex Kerr, Retronym and the rest of the Justice League.)