I want to have non exhaustive when's on a sealed c...
# announcements
p
I want to have non exhaustive when's on a sealed classes to be an error, is that possible somehow?
g
Only if
when
is expression, you can force this
There is feature request to provide language support for this https://youtrack.jetbrains.com/issue/KT-12380
p
I know that; I'm talking about inspections
On an enum it highlights, on a sealed class it doesn't
g
yes, this is quite new inspection
saw it only recently
p
image.png
g
yeah, Saw it
But sealed class wouldn’t be an “error”, but “warning”
p
Warning would be fine; I can set warningAsErrors
With my programming style, missing sealed cases is 95% of the time a programming error
s
There is kind of a hacky thing some folks do when they want an exhaustive
when
without necessarily writing their code such that it results in an assignment -
Copy code
fun Any?.exhaustive() = Unit

when (sealedInstance) {
  ...
}.exhaustive()
not exactly the most elegant solution, but one nonetheless
g
I prefer just call .toString or maybe use
.javaClass
as suggested someone in sealed when issue,
Any?.exhaustive()
pollutes autocomplete
s
¯\_(ツ)_/¯ imo calling either of those doesn’t clearly convey intent, plus it’s very rare for me to define any extension to
Any?
, so “pollution” seems like a strong word for literally one method. I agree it’d be nice to have this as a smarter language feature, but I personally don’t see that much issue with
.exhaustive()
g
Yes, I completely agree, there is no good solution
We just choose from many not perfect solutions
so “pollution” seems like a strong word for literally
You will have this extension on any type, I would say that this is pollution
g
You can write your own function that works like an exhaustive when. You still have to update your function if you add or remove an item from your enum, but you can throw an exception if nothing matches and at least you only have to change one place. https://github.com/GlenKPeterson/Paguro/blob/2017-09-17_Kotlin/src/main/java/org/organicdesign/fp/oneOf/Or.kt#L74
p
Sure I can do all that. But: there is already the intention giving a hint on it - can't it just be raised to a warning?