https://kotlinlang.org logo
#detekt
Title
# detekt
l

Luca Nicoletti

02/24/2023, 2:32 PM
Has anyone made a custom rule/does a default one exists that check for
when
statement orders? I’m looking to have all
objects
of a sealed class/interface coming first, then the data classes, so my when(s) would look like:
Copy code
when (a) {
   object1 -> {}
   object2 -> {}
   object3 -> {}
   is dc1 -> {}
   is dc2 -> {}
}
And not with
is
mixed between all the statements
c

Chris Lee

02/24/2023, 2:35 PM
branches in a when expression are evaluated in the order provided; would be questionable to force an arbitrary order that may not align with the logic of the expression.
l

Luca Nicoletti

02/24/2023, 2:37 PM
Can you explain better? The page says
matches its argument against all branches sequentially until some branch condition is satisfied.
Meaning that it try from the first until there’s a match, then stops, right?
c

Chris Lee

02/24/2023, 2:37 PM
that’s correct.
l

Luca Nicoletti

02/24/2023, 2:37 PM
If I have a
sealed interface
with
3 objects
and
2 data classes
my instance will be either an object (only one), or a data class
I don’t see a problem in having some code order there 🤷🏼, trying to match object firsts, and then data classes
c

Chris Lee

02/24/2023, 2:39 PM
yes, but it can satisfy any number of conditions. For example, if classes implement several interfaces (A, B, C) you may have logic where
is C
is checked before
is A
. Also, performance may be a consideration - will often organize when expressions knowing that certain conditions are frequently hit (or not).
l

Luca Nicoletti

02/24/2023, 2:40 PM
We don’t have that structure for now, so, do you know if there is a way or not?
c

Chris Lee

02/24/2023, 2:41 PM
No idea if there is a way. Suggesting it won’t be common or prudent for the reasons above.
l

Luca Nicoletti

02/24/2023, 2:41 PM
Thanks 🙂
b

Brais Gabin

02/24/2023, 4:45 PM
That's completely doable but as far as I know there's nothing like that implemented.
In general I prefer to group the when in a logical order. First loading state, the errors and then success. Or something similar. The problem is that a rule is difficult to umpteenth to do something like that. Is the same as keep the related functions together.
l

Luca Nicoletti

02/26/2023, 8:54 AM
Any suggestions/hints on how to get started with that?
b

Brais Gabin

02/26/2023, 1:02 PM
Use this template https://github.com/detekt/detekt-custom-rule-template and look at detekt for a rule that does something similar. In your case a rule related with
when
. Copy&paste that rule to your project and edit it until it does what you want.
In general is a really good idea to write the test first.
And I'm not a tdd fan. Tests first works really well with detekt
16 Views