Closed kyay10 closed 1 year ago
Thanks for the detailed use case, issue and PR!
Although in normal code I'd usually prefer to leave out the is
in when statements for objects, these two should be overall pretty equivalent:
when (object) {
FirstObject -> // ...
SecondObject -> // ...
}
when (object) {
is FirstObject -> // ...
is SecondObject -> // ...
}
Instead of having a property useIsChecksForSealedObjectComparison
, it might make sense to switch to is
checks everywhere in the generated code for situations like this. That should fix your use case without needing an additional argument, and I don't think there'd be any downsides to doing so?
It's technically ever so slightly different in that, if a different instance of the sealed object is created through reflection (usually as a result of a serialization framework), it would change the behaviour of code that previously would throw errors (due to NoWhenBranchMatchedException) to not throw anymore. It's surprising behavior that that code would throw in the first place, so I would agree that changing to is
checks is the way to go.
@alexvanyo Done! I've changed the code to use is
checks, and I've updated the tests and docs to reflect that. Please check #130 and suggest any needed changes!
That behavior is surprising, I think the is
method is better (or at least is a bit more robust to these edge cases).
I also saw in the updated Kotlin docs on data object
s they even have a mention for using ==
instead of ===
for similar reasons. I'll take a look at #130 when I have a chance!
Minimal reproducer
A little context about my use-case: We're using sealed classes as Flags, and so it's common for us to want each object to have an integer representation that is 1 shifted left by its ordinal. This exception happens because during the initialization of the
INSTANCE
s for the objects, theordinal
extension property is accessed, which internally compares the object (using equality) against the instances of the objects inside the sealed class. A simple workaround for this is to turni
into a computed property, but that makesi
get recomputed on every call, which adds the cost of all the equality checks thatordinal
does internally. It would be appreciated if an option in the plugin could be provided that, instead of comparing the objects by equality, doesis
checks inside the ordinal property (so that this issue is prevented). I'm not super familiar with ksp and kotlinpoet, but I can attempt at making a PR that solves this.