Make a type Comparable with itself through extension operator overload

I’m handling lists of UByte, which I call Code (currently through a typealias), and which I need to be comparable with one another (through a compareTo function I implemented). That makes lists of UByte comparable among themselves, when you use my code. Which is functionnally equivalent of implementing Comparable<Code> or Comparable<*>.
But some features which depend on being Comparable<*>, for instance the List.min method, don’t work because the compiler (or is that only the syntax highlighter ?) doesn’t get that List<UByte> is now Comparable.
How can I make it work ?

You can’t implement an interface externally sadly. Alternatives are either making Code a value class, or making a new List.min method that takes a Comparator

1 Like

Value classes may solve my issue. I would need to do val code = Code(list) in all my functions, but that would become a noop in actual compiled code, right ?

1 Like

Indeed. However, when using it as a Comparable, sometimes there will be boxing (in particular, direct usages might be fine? Also inline methods generally won’t cause such boxing).

1 Like

You would have to wrap each item separately, not the whole list. Also, value/inline class will be entirely ineffective in this case. Each item will be wrapped anyway (which isn’t necessarily a problem - GC is optimized for short-lived objects).

edit:
Ahh, sorry, never mind, I misread your initial post. The whole list is a Code, not individual items.

2 Likes