I dont know why I haven't asked the community this...
# codingconventions
g
I dont know why I haven't asked the community this before: when using a `when`_-thing_ over an enum, I can use a when-statement but I would prefer to use a when-expression so that I can force future maintainers to handle new additions to the enum. This is actually one of my favourite features of kotlin; if you change an enum/sealed-class you can get the compiler to alert maintainers to where that new type might break code. for a while I would force when-statements into when-expressions by writing
val dc = when(sealedTypeInstance) {...}
, where 'dc' is 'dont care', but not everyone at my company would know that and might wonder why there is an unused variable and remove it. Lately I've been writing
when(sealedTypeInstance) { ... } as Any?
which is a little nicer since its on the tail, and is cryptic enough to not have a junior remove it, but still isnt great. What do you guys do? Does a kotlin style guide have a suggestion for me?
e
if you're on Kotlin 1.5.30+, you can already live in the future (as far as this new language feature goes). otherwise https://github.com/cashapp/exhaustive lists a number of alternatives
👍 2
j
Don't use when :) use the enum strategy pattern. Add a unit returning function as a constructor parameter in the enum. Then every new enum must define that function.
p
@Jacob Such strategies put quite a burden upon the enum, especially if you have a lot of code using it. I would say visitors would be a better alternative (at least the enum doesn't need to know about things outside of its own scope), but still cumbersome. The very reason that enums/sealed types allow exhaustive when.