I want to ensure that a certain parameter value is not set twice in the set of enum constants. The best place would be a Set in the companion object to store used values, but the Set property of the companion object would be initialized after the enum constants!
So the best I’ve come up with is a Set outside of the enum in the same file:
If this is something you only need once this is probably the best solution. If you need this on lot’s of enums you could write an annotation processor or compiler plugin to do this check at compile time.
My example was a bit simplistic, in fact there is more than one parameter.
Thank you both for your assessment. I will keep as is for now, since it is not worth to develop an annotation processor or compiler plug-in, but I like the idea.
I second using a unit test in this case, as it avoids any runtime overhead. I do suggest using a library like AssertJ or assertk so that you write assertThat(Thing.values().groupBy { it.id }.filter { it.value.size > 1 }).isEmpty(), which will give you a useful error message of exactly which ids are used multiple times, and which enum values have each of those ids.
@kyay10 Interesting idea to derive the companion object from a class. However, this will create a runtime error, and only when Thing is actually being used, so I’d definitely prefer a unit test. My suggested new syntax would do the uniqueness check at compile time.