02/14/2022, 1:53 PM
Hi , is it possible to build a
inline class
pool that returns same reference ? Related link : Play ground : I am building a carousel-like Int , naming 
 , which restrict any Int value to 
 . That is 
Three.of(1) == Three.of(4)
Three.of(0) == Three.of(3)
   . I use a prebuild  array to simulate caching , hoping they get the same reference
Copy code
private val array by lazy {
  arrayOf(Three(1), Three(2), Three(3))
But it seems it doesn't work. When comparing reference 
 , it complains 
Identity equality for arguments of types Three and Three is forbidden
 , which is counter-intuitive .


02/14/2022, 3:14 PM
Why? This goes against very idea of value classes - value's class value is it's identity. If two values are equal, they are identical. When you declare class a value class, you are basically saying "Okay, this class has no identity beyond the data it holds", an identity operator on it doesn't make sense - if it existed, it would do exactly same thing as equals operator
That's from theory standpoint, from more practical one: Value (or Inline) classes can be inlined as compiler wishes. Now if you have an inlined
x: Int
and not inlined
y: Three
how would you compare they have same identity (when original code had
x === y
?) You can't - the only reason the inlining can be consistent is that this operation is invalid. Equals operator is easy to do:
x == y
in original code would just turn to
x == y.value
in inlined one.
🤔 1

Youssef Shoaib [MOD]

02/15/2022, 6:51 PM
For your
class btw, it's probably best to use an enum instead with 3 values


02/18/2022, 1:16 AM
It makes sense , thanks