Inline classes, strings and intern

Stephen Colebourne scolebourne at
Fri Dec 20 10:39:15 UTC 2019

If I declare an inline class (examplar syntax):

_Inline_ class StrPos (String str, int pos) {}

then the strings are compared with `==` not `.equals()`. Thus:

 a = new StrPos("abba", 2)
 b = new StrPos("abbac".substring(0, 4), 2)
 a == b  -> false
 a.equals(b)  -> true

If I were the author is such a class, I might not like that. But there
is a "simple" solution - interning. If I call `String.intern()` on the
string in the constructor of the inline class then a == b would now be

Great! Except that my understanding is that interning is frowned upon
these days. Obviously the same interning approach could be made to
work for any type (such as using Guava's `Interners` class), but it
seems particularly relevant to discuss it wrt `String.intern()`
because it is built in and has special JVM global behaviour.

It seems to me that because `String.intern()` exists and is easy to
use, it could be widely abused to get the desired == behaviour for
inline classes. Is this a real problem that needs more thought? Or not
something to worry about?


More information about the valhalla-dev mailing list