3 ms·
Handwavy explanation: A stable value is used as a static constant, with the difference being that you can initialize it at runtime. Once initialized it is treat
by sagacity 1y ago
Handwavy explanation: A stable value is used as a static constant, with the difference being that you can initialize it at runtime. Once initialized it is treated as fully constant by the JVM. It's similar to something like lateinit in Kotlin, except on the JVM level.
Records are also immutable, but you can create them and delete them throughout your application like you would a regular class.
- gavinray 1y agoBut this is also achievable with static init methods on records and value classes, right? record Rational(int num, int denom) { Rational { int gcd = gcd(num, denom); num /= gcd; denom /= gcd; } }
- sagacity 1y agoHow would you do the same thing with the late initialization of, say, a HashMap where you don't control the constructor?
- pkulak 1y agoSo every time you take the hash of a string you leak 4 bytes of memory??? I assume it's static in the context of it's containing object. So, it will be collected when it's string is collected.
- nimrody 1y agoNo. The string hash is stored as part of the String object. It is initialized to 0 but gets set to the real hash of the string on first call to hashCode() (which is why it will be computed over and over again if your special string happens to hash to 0)
- leksak 1y ago> It's similar to something like lateinit in Kotlin, except on the JVM level. What level are you suggesting lateinit happens at if not on the JVM?
- Tmpod 1y agoI assume they mean this feature is built into the JVM itself, whereas Kotlin's lateinit more or less "just" desugars into code you could otherwise write yourself.
- w10-1 1y ago> used as a static constant Yes, but remind people it's not static in the sense of being associated with the class, nor constant for compile-time purposes. Perhaps better to say: A stable value is lazy, set on first use, resulting in pre- and post- initialization states. The data being set once means you cannot observe a data change (i.e., appears to be immutable), but you could observe reduction in resource utilization when comparing instances with pre-set or un-set values -- less memory or time or other side-effects of value initialization. So even if data-immutable, a class with a stable value ends up with behavior combinations of two states for each stable value. Immutable records or classes without stable values have no such behavior changes. But, writ large, we've always had this with the JVM's hotspot optimizations. For String, it becomes significant whether hashcode is used when calculating equals (as a fast path to negative result). If not, one would have two equal instances that will behave differently (though producing the same data), at least for one hashcode-dependent operation.
- owlstuffing 1y agoRight. Oracle should reconsider the naming here: stable -> lazy