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

Kirill Zhukov

03/29/2023, 6:25 PM
Is there a rule that I can reuse for catching unused declarations? A common pattern in my codebase is to set a state like so:
state = FooState
. Sometimes it’s easy to typo and forget to set the state:
FooState
. All of my states are derived from a common
State
type, so wondering if there is a rule that makes sure that types of the
State
are used.
c

chao

03/29/2023, 7:59 PM
I am wondering if you’d mind elaborating your example a bit - I am wondering if this is a false positive for https://detekt.dev/docs/rules/style#unusedprivatemember
t

twisterrob

03/30/2023, 3:05 PM
This is more similar to
@CheckReturnValue
. I don't think there's a Detekt rule that checks dangling objects (or just never written this kind of code). @chao afaiu the use case is:
Copy code
class SomethingC
object SomethingO
class Other {
    fun f() {
        this.state = SomethingO // ok, SomethingO.INSTANCE is used
        this.state = SomethingC() // ok, constructor's "return value" is used
        SomethingO // flag
        SomethingC() // flag
    }
}
@Kirill Zhukov I think you can write your own rule pretty easily with type resolution. Find all the constructor calls / object references to classes extending state, and then validate that they're part of an assignment, a function call, or return statement/expression. The only thing I don't know how to detect is
.let { MyState(it) }
or
when { true -> MyState; else -> error() }
, because these usages are not an assignment, nor a function call.
k

Kirill Zhukov

04/03/2023, 5:15 PM
That’s right, ideally I would want something similar to
@CheckReturnValue
🙂
8 Views