https://kotlinlang.org logo
Title
p

Paul Woitaschek

03/28/2019, 6:45 AM
I want to have non exhaustive when's on a sealed classes to be an error, is that possible somehow?
g

gildor

03/28/2019, 6:52 AM
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

Paul Woitaschek

03/28/2019, 7:02 AM
I know that; I'm talking about inspections
On an enum it highlights, on a sealed class it doesn't
g

gildor

03/28/2019, 7:06 AM
yes, this is quite new inspection
saw it only recently
p

Paul Woitaschek

03/28/2019, 7:06 AM
g

gildor

03/28/2019, 7:06 AM
yeah, Saw it
But sealed class wouldn’t be an “error”, but “warning”
p

Paul Woitaschek

03/28/2019, 7:36 AM
Warning would be fine; I can set warningAsErrors
With my programming style, missing sealed cases is 95% of the time a programming error
s

Shawn

03/28/2019, 8:53 AM
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 -
fun Any?.exhaustive() = Unit

when (sealedInstance) {
  ...
}.exhaustive()
not exactly the most elegant solution, but one nonetheless
g

gildor

03/28/2019, 8:55 AM
I prefer just call .toString or maybe use
.javaClass
as suggested someone in sealed when issue,
Any?.exhaustive()
pollutes autocomplete
s

Shawn

03/28/2019, 9:01 AM
¯\_(ツ)_/¯ 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

gildor

03/28/2019, 9:01 AM
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

glenkpeterson

03/28/2019, 1:31 PM
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

Paul Woitaschek

03/28/2019, 2:23 PM
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?