Repository navigation
Home
Rules of detekt-rules, described as of version 2.1.0.
| Rule | Active by default | Needs type resolution |
|---|---|---|
RouteWiringMethodNaming |
yes | no |
MapperFileNaming |
yes | no |
PayloadArgumentName |
yes | no |
UseSurfaceModifier |
yes | no |
UseOnStartEmit |
no | no |
ComponentFunctionCall |
no | no |
BlockingSqlDelightCall |
yes | yes |
ImmutableDataClass |
yes | no |
MissingTypeDeclaration |
yes | yes |
NullableValueClassProperty |
no | no |
ConstantsNotAtBottom |
no | no |
InconsistentWhenTypeCheck |
no | yes |
SealedClassCouldBeEnum |
no | yes |
UnusedLetResult |
no | yes |
CoroutineScopeNotCancelled |
no | no |
CancellationExceptionNotRethrown |
no | yes |
PublicSuspendFunctionInReactiveModel |
no | yes |
UnhandledViewIntent |
no | yes |
"Active by default" is the state in the configuration bundled with the rule set; every rule can be turned on or off
in your detekt-config.yml. The nine rules added in 2.1.0, from NullableValueClassProperty to
UnhandledViewIntent, are not active by default: enable the ones you need.
Rules which need type resolution only report when detekt has type information. On
detekt 1 that is the detektMain and detektTest tasks,
or detekt-cli --classpath ...; in a plain detekt task such a rule reports nothing. On detekt 2 they only run
with --analysis-mode full. The other rules work on syntax only.
The rule set id (kode), the rule ids, options and behaviour are the same in both artifacts,
ru.kode:detekt-rules:2.1.0 (detekt 1.22.0 - 1.23.8) and ru.kode:detekt-rules-detekt2:2.1.0
(detekt 2.0.0-alpha.6).
Active by default.
A function of a wiring class which passes an event to the coordinator is a navigation handler, and its name should
say so: it has to start with navigateOn.
Non-compliant:
class ProfileWiring(private val coordinator: Coordinator) {
// ❌ calls coordinator.handleEvent, but is not named navigateOn...
fun openSettings() {
coordinator.handleEvent(Event.SettingsRequested)
}
}Compliant:
class ProfileWiring(private val coordinator: Coordinator) {
// ✅
fun navigateOnSettingsRequested() {
coordinator.handleEvent(Event.SettingsRequested)
}
}The rule looks at every function whose nearest enclosing class has Wiring in its name, also at functions of its
companion object and at local functions. A nested class is judged by its own name.
Not reported:
- a function which calls
handleEventof something else (router.handleEvent(...)) - a function of a class without
Wiringin the name
Limits: the call is found in the text of the function, as coordinator.handleEvent or Coordinator.handleEvent.
So any name which ends with it counts (flowCoordinator.handleEvent(...)), and so does a comment with this text.
Active by default.
A file with mappers usually holds several of them, so its name should end with Mappers, not with Mapper.
- ❌
ProfileMapper.kt,Mapper.kt - ✅
ProfileMappers.kt
Only the file name is checked, the content does not matter. MapperUtils.kt and SomeFeaturemapper.kt are not
reported.
Active by default.
In an onEach(...) { } block of a state machine the last lambda parameter of transitionTo and action holds the
value of the event. payload says nothing about what the value is: name it after its meaning.
Non-compliant:
onEach(intent(Intents::onTextChanged)) {
// ❌ what is the payload?
transitionTo { state, payload -> state.copy(text = payload) }
// ❌
action { _, _, payload -> model.validate.start(payload) }
}Compliant:
onEach(intent(Intents::onTextChanged)) {
// ✅
transitionTo { state, text -> state.copy(text = text) }
// ✅
action { _, _, text -> model.validate.start(text) }
}The rule checks the second parameter of the transitionTo lambda and the third parameter of the action lambda,
wherever in the onEach block the call is (inside an if, a run and so on).
Not reported:
- a parameter named
payloadat another position (transitionTo { payload, state -> }) -
transitionToandactionoutside anonEachblock - an
onEachwhich is not called asonEach(event) { }: without the argument, with two arguments, with the lambda inside the parentheses - a
transitionTowhose first argument is not the lambda (transitionTo(reducer) { state, payload -> })
Active by default.
A shaped background combined with clickable, clip or shadow has to repeat the shape in every modifier and to
put them in the right order. The surface modifier does it in one call.
Non-compliant:
@Composable
fun Card() {
Box(
// ❌ background with a shape together with clickable and clip
modifier = Modifier
.clickable(onClick = {})
.background(shape = RoundedCornerShape(12.dp))
.clip(RoundedCornerShape(12.dp)),
)
}Compliant:
@Composable
fun Card() {
// ✅
Box(modifier = Modifier.surface(shape = RoundedCornerShape(12.dp), onClick = {}))
}A chain is checked when it starts with Modifier or modifier and is written in a @Composable function, also in
a member function and in a local function of a composable one. A chain nested in the arguments of another chain is
checked on its own.
Not reported:
- a
backgroundwithout theshapeargument - a shaped
backgroundwithoutclickable,cliporshadowin the same chain - chains outside composable functions
Limits: only the named shape = ... argument is seen, background(Color.Red, shape) is not reported.
Not active by default.
onStart { emit(value) } is what the onStartEmit(value) extension is for.
Non-compliant:
// ❌
val states = updates.onStart { emit(State.Loading) }Compliant:
// ✅
val states = updates.onStartEmit(State.Loading)emit is looked for among the statements of the lambda, so a lambda which does something else too is reported as
well. Every onStart of a chain is reported.
Not reported:
- an
onStartwhose lambda does not emit (onStart { log() }) - an
emitnested in another statement (onStart { if (ready) emit(3) }) - a function reference (
onStart(::emitDefault)) - an
onStartcall without a receiver
Limits: the functions are matched by name, the rule does not check that the receiver is a Flow.
Not active by default.
componentN() functions exist for destructuring declarations. Called directly, they hide which property is read.
Non-compliant:
// ❌
val name = user.component1()Compliant:
// ✅
val name = user.name
// ✅
val (name, age) = userEvery component1(), component2() ... call with a receiver and without arguments is reported, each call of a
chain separately.
Not reported:
- names which are not generated ones:
component0(),component01() - a call with arguments or without a receiver
Active by default. Needs type resolution.
SqlDelight queries and transactions block the thread. In a suspend function they have to be moved off the caller's
dispatcher with withContext(Dispatchers.IO).
Non-compliant:
suspend fun saveUser(user: User) {
// ❌ blocks the caller's thread
database.userQueries.insert(user.id, user.name)
}Compliant:
suspend fun saveUser(user: User) {
withContext(Dispatchers.IO) {
// ✅
database.userQueries.insert(user.id, user.name)
}
}A call is reported when the called function is a member of Transacter of the configured package or of its
subtype (the database and the generated queries classes are such), seen from the receiver: inherited members and
overrides count. The call may be anywhere in the suspend function, also in a lambda or in a local function which
is not suspend itself. A nested suspend function is checked on its own.
Not reported:
- calls in a function which is not
suspend - calls inside a
withContext(...)call, also whenwithContextencloses the local function with the call - constructor calls
-
toString(),hashCode()andequals()
Limits: withContext is matched by name and its dispatcher is not checked.
// in detekt-config.yaml
kode:
BlockingSqlDelightCall:
active: true
sqlDelightPackage: 'app.cash.sqldelight'sqlDelightPackage is the package of Transacter. The value above is the default.
Active by default.
A data class of a UI layer is passed to composable functions. Without @Immutable the Compose compiler may treat it
as unstable and recompose its readers more often than needed.
Non-compliant:
package ru.kode.app.feature.profile.ui
// ❌
data class ViewState(val name: String)Compliant:
package ru.kode.app.feature.profile.ui
// ✅
@Immutable
data class ViewState(val name: String)A data class is checked when one of the segments of its package is exactly ui, at any depth
(ru.kode.ui.profile too). Nested data classes are checked as well. The annotation may be written with its fully
qualified name.
Not reported:
- data classes of other packages
- classes which are not data classes
@Stable does not count: a data class with it is still reported.
// in detekt-config.yaml
kode:
ImmutableDataClass:
active: true
ignoreDescendantsOf: [ 'ScreenEvent', 'ru.kode.app.core.ui.ViewEvent' ]ignoreDescendantsOf (empty by default) skips data classes which have one of these types among the supertypes
written in their declaration. A type is given by its short or fully qualified name. Only direct supertypes count: a
data class which inherits such a type through another class is still reported.
The NonImmutableDataClassParameter rule of
detekt-rules-compose
is related: it reports at the parameter of a composable function, wherever the data class is declared. When both
rules are active, set its ignoredPackageSegments: [ 'ui' ], so the classes of ui packages are left to
ImmutableDataClass and are not reported twice.
Active by default. Needs type resolution.
A public member without an explicit type gets the type inferred from its initializer or body. The reader has to guess it, and an edit of the body silently changes the API of the class.
Non-compliant:
class UserRepository {
// ❌ public property without a type
val users = MutableStateFlow(emptyList<User>())
// ❌ public function without a return type
fun findUser(id: String) = users.value.find { it.id == id }
}Compliant:
class UserRepository {
// ✅
val users: MutableStateFlow<List<User>> = MutableStateFlow(emptyList())
// ✅
fun findUser(id: String): User? = users.value.find { it.id == id }
}Members of class bodies are checked, nested classes and companion objects included. The message names the inferred
type: Missing explicit type declaration for public value 'users: MutableStateFlow<List<User>>'.
Not reported:
-
private,protectedandinternalmembers - functions which return
Unit - top-level declarations, members of
objectdeclarations and local declarations
// in detekt-config.yaml
kode:
MissingTypeDeclaration:
active: true
ignoreInClassesDerivedFrom: [ 'ViewIntents' ]
ignoreInInterfacesDerivedFrom: [ 'Component' ]
ignorePropertiesOfType: [ 'Int', '^Task\d+<.*>$' ]All three options are empty by default.
-
ignoreInClassesDerivedFromskips classes which have one of these supertypes, directly or not, a class or an interface. Simple names. -
ignoreInInterfacesDerivedFromskips classes which directly implement one of these interfaces. Simple names. -
ignorePropertiesOfTypeskips properties whose inferred type matches one of these regular expressions. The expression has to match the whole type as the message shows it, type arguments included.
Not active by default.
A value class which wraps a nullable type has two ways to be empty, null and a wrapper of null. Keep the
property non-null and make the value class itself nullable where a value may be absent.
Non-compliant:
// ❌
@JvmInline
value class UserId(val value: String?)Compliant:
// ✅
@JvmInline
value class UserId(val value: String)
val id: UserId? = nullThe finding is put on the property.
Not reported:
- a nullable type argument of a non-null type (
value class Names(val value: List<String?>)) - classes which are not value classes
Not active by default.
Constants are details: they go below the code which uses them. In a file that is the bottom of the file, in a class that is the companion object, declared last.
Non-compliant:
// ❌ a constant above a declaration which is not a property
private const val PAGE_SIZE = 20
class Pager {
// ❌ a companion object with constants above other members
companion object {
const val FIRST_PAGE = 1
}
fun load(page: Int) = Unit
}Compliant:
class Pager {
fun load(page: Int) = Unit
// ✅
companion object {
const val FIRST_PAGE = 1
}
}
// ✅
private const val PAGE_SIZE = 20At the top level a const val is misplaced when anything but a property is declared below it, right after it or
later. Other properties may be mixed with the constants at the bottom. In a class, a companion object with at least
one const val has to be the last declaration of the class; nested classes, interfaces and enum classes are
checked too.
There is one finding per file, on the first misplaced constant, and one per class, on the companion object.
Not reported:
- a file which has only constants and properties
- a companion object without constants, wherever it is
- a nested object which is not a companion
Not active by default. Needs type resolution.
A when over a sealed type checks classes with is. An object may be checked both ways, is State.Loading and
State.Loading, and a when which mixes them reads as if the branches did different things. They nearly do: the
second form calls equals.
Non-compliant:
when (state) {
is State.Content -> showContent(state.items)
// ❌ compared by equality, the other branch is a type check
State.Loading -> showProgress()
}Compliant:
when (state) {
is State.Content -> showContent(state.items)
// ✅
is State.Loading -> showProgress()
}Only a when with a subject (also when (val x = ...)) and with at least one is condition is checked. In it a
condition is reported when it is a plain or qualified name, also in parentheses or one of several conditions of a
branch, which resolves to an object declaration (a data object and an object of a library too) or to a type alias
of one.
Not reported:
- a
whenwith equality checks only, and awhenwithout a subject - constants and enum entries
- companion objects: a property of one (
Dp.Unspecified), a class name which stands for its companion, a type alias of such a class or of the companion - literals,
null, ranges, calls and chains with a call (State.create().Loading) - names which do not resolve
Not active by default. Needs type resolution.
A sealed type whose inheritors are all objects without state is an enum written the long way. An enum class gives
entries, name and ordinal for free.
Non-compliant:
// ❌ only stateless objects inside
sealed interface Direction {
data object Up : Direction
data object Down : Direction
}Compliant:
// ✅
enum class Direction { Up, Down }A sealed class or interface is reported when it has no type parameters and no superclass, and has at least two
inheritors, each of them an object or a data object which has no other supertype and declares no properties of
its own. The inheritors are found in whatever file they are declared. Overridden members do not make an object
stateful.
Not reported:
- a sealed type with an inheritor which is a class
- an inheritor with a property of its own, or with one more supertype
- a generic sealed type, and a sealed class which extends another class
- a sealed type with fewer than two inheritors, or one inherited by its own companion object
Limits: a superclass is seen in the supertype list of the sealed class. One which is called only as super(...) of
secondary constructors is not, and such a class is reported.
Not active by default. Needs type resolution.
let exists to turn a value into another one. When the result is thrown away, the call is a null check or a side
effect in disguise: an if or also says it directly.
Non-compliant:
fun show(error: String?) {
// ❌ the result of let goes nowhere
error?.let { showToast(it) }
}Compliant:
fun show(error: String?) {
// ✅
if (error != null) showToast(error)
// ✅
error?.also { showToast(it) }
}A let { } call with a receiver is reported when it stands in statement position:
- in a block, not as its last statement, or as the last statement of a function body, a getter, an
initblock, a secondary constructor or afinallyblock - in a branch of an
if,when,tryorcatchwhich is itself a statement - in a loop body
- as the last statement of a lambda which returns
Unit, likeforEach { item -> item?.let { } }orval action: () -> Unit = { error?.let { it.length } }
Parentheses and labels around the call do not hide it. The finding is put on let.
Not reported:
- a
letwhose result is used: assigned, returned, passed as an argument, continued (?.let { }?.length,?.let { } ?: fallback), or the value of an expression body or of anif/when/trywhich is used - the last statement of a lambda which returns a value (
map { it?.let { } },run { error?.let { } }) -
letwith a function reference (value.let(::println)), andletwithout a receiver -
also,runand other scope functions
Limits: the lambda of a call which does not resolve gets its type from its last statement, so a let there is taken
as the result of the lambda and is not reported.
Not active by default.
A class which creates a CoroutineScope owns it. If the class never cancels the scope, the coroutines launched in
it outlive the class.
Non-compliant:
class Player {
// ❌ created here and never cancelled
private val scope = CoroutineScope(Dispatchers.Main)
fun play() {
scope.launch { /* ... */ }
}
}Compliant:
class Player {
private val scope = CoroutineScope(Dispatchers.Main)
fun play() {
scope.launch { /* ... */ }
}
// ✅
fun release() {
scope.cancel()
}
}The rule looks at the properties of a class which are initialized with CoroutineScope(...) or MainScope() and
searches the class for a cancel call on the property. The code of a nested class does not count, the code of an
anonymous object does.
What counts as a cancel:
- a call on the scope or on something read from it:
scope.cancel(),this.scope.cancel("closed"),scope?.cancel(),(scope).cancel(),scope.coroutineContext.cancel(),scope.coroutineContext[Job]?.cancel() - a call on a job the scope was built from:
job.cancel()forCoroutineScope(Dispatchers.Main + job) - a
cancel()in a block which has the scope as its receiver:with(scope) { cancel() },scope.run { cancel() },scope.apply { cancel() }, also inside a lambda of such a block which does not start a coroutine - a
cancelon the parameter ofletoralso:scope?.let { it.cancel() },scope.also { s -> s.cancel() }
What does not count:
- cancelling the result of a call:
scope.launch { }.cancel(),scope.coroutineContext.job.children.first().cancel() cancelChildren()- a
cancel()inside a coroutine builder, which cancels that coroutine:with(scope) { launch { cancel() } }. The builders arelaunch,async,coroutineScope,supervisorScope,withContext,withTimeout,withTimeoutOrNullandrunBlocking - a
cancel()without a receiver outside such a block, also inscope.let { cancel() } - a
cancelon a property of another instance (player.scope.cancel())
Not reported:
- a scope built from a parent, which is cancelled together with it:
CoroutineScope(parent.coroutineContext),CoroutineScope(parent.coroutineContext + Dispatchers.IO),CoroutineScope(SupervisorJob(parentJob)),CoroutineScope(Job(parent = parent.coroutineContext[Job])) - a non-private scope of an
open,abstractorsealedclass: a subclass may cancel it - a scope of an
object: it lives as long as the process - a scope which is not a property initialized in the class: one taken as a constructor parameter, a top-level or a local one
A scope with a parent is still reported in two cases. The first is a job of its own which replaces the job of the
parent context: CoroutineScope(parent.coroutineContext + SupervisorJob()). The second is a parent job which is a
property of the same class, created without a parent and never cancelled:
class Player {
private val job = Job()
// ❌ neither scope nor job is cancelled
private val scope = CoroutineScope(SupervisorJob(job))
}Limits: everything is matched by name within one class, without types.
- A scope which is cancelled by the object it is handed to is reported.
- A scope created in
by lazy { }or in aninitblock is not seen. - A subclass which gets a non-private scope is trusted to cancel it and is not checked.
- A
cancel()in a lambda of another function which has its own scope as the receiver, nested in a block of the scope, still counts. - A parameter of a nested lambda which shadows the
let/alsoparameter is taken for the scope.
Not active by default. Needs type resolution.
A coroutine is cancelled with a CancellationException thrown from a suspension point. A catch which swallows it
lets the cancelled coroutine go on working, and catch (e: Exception) does it without anyone noticing.
Non-compliant:
suspend fun load(): Profile? {
return try {
api.profile()
} catch (e: Exception) {
// ❌ swallows the cancellation too
null
}
}Compliant:
suspend fun load(): Profile? {
return try {
api.profile()
} catch (e: CancellationException) {
// ✅ rethrown before the broad catch
throw e
} catch (e: Exception) {
null
}
}
suspend fun loadOrNull(): Profile? {
return try {
api.profile()
} catch (e: Exception) {
// ✅ throws when the coroutine is cancelled
coroutineContext.ensureActive()
null
}
}The rule checks a try whose block calls a suspend function:
- directly, a call of a value of a suspend function type (
action()) and of a suspendinginvokeoperator included - in a lambda or an anonymous function which an
inlinefunction runs in place (forEach { },run { }, also nested ones)
The try may be in a suspend function or in a suspend lambda (scope.launch { try { } catch ... }).
In such a try the first catch of CancellationException, Throwable, Exception, RuntimeException or
IllegalStateException (the supertypes of CancellationException) is reported, unless its body
- throws the caught exception (
throw e, alsoif (e is CancellationException) throw e), - calls
ensureActive(), - or calls one of
rethrowFunctions.
There is one finding per try, on the catch clause. When a catch (e: CancellationException) rethrows, the
clauses below it are fine.
Not reported:
- a
trywithout suspending calls, or with them only incatchorfinally - a
catchof a narrower type (IOException) - a suspending call in a lambda passed to a
noinlineorcrossinlineparameter, like the lambda ofFlow.map, or in a lambda which starts another coroutine (scope.launch { fetch() }) - a suspending call in a local function or in an object declared in the
tryblock - functions of a
@RestrictsSuspensionclass, likeyieldinsequence { }: they suspend a generator, which nobody cancels - calls which do not resolve
Wrapping does not count as a rethrow: throw IllegalStateException(e) is reported.
Limits:
- Only calls are suspension points. A
trywhich suspends only through an operator, an infix call, aforloop over a channel or a delegated property is not reported. - The caught types and the rethrow are matched by name. A
throw eunder any condition, or in a lambda which never runs, counts as a rethrow.
detekt has a similar rule of its own, SuspendFunSwallowedCancellation. In detekt 2.0.0-alpha.6 it checks
try / catch as well, in detekt 1.23.8 it covers runCatching only. This rule covers
try / catch, and does not look at runCatching.
// in detekt-config.yaml
kode:
CancellationExceptionNotRethrown:
active: true
rethrowFunctions: [ 'rethrowCancellation' ]rethrowFunctions (empty by default) holds names of functions whose call in the catch counts as a rethrow.
Not active by default. Needs type resolution.
A reactive model exposes its work as tasks, which are started explicitly and observed as flows. A public suspend
function goes around that: the caller has to bring a scope of its own, and nobody else sees the state or the result
of the work.
Non-compliant:
class ProfileModel(
private val repository: ProfileRepository,
scope: CoroutineScope,
) : ReactiveModel(scope) {
// ❌
suspend fun load(): Profile = repository.profile()
}Compliant:
class ProfileModel(
private val repository: ProfileRepository,
scope: CoroutineScope,
) : ReactiveModel(scope) {
// ✅ a task
val load = task<Unit, Profile> { repository.profile() }
// ✅ not public
private suspend fun refresh() = repository.refresh()
}A public suspend member function is reported in a class which is derived from one of baseClasses, directly or
through other classes. Nested models are checked too.
Not reported:
-
private,internalandprotectedfunctions -
overridefunctions - local
suspendfunctions - the base class itself
// in detekt-config.yaml
kode:
PublicSuspendFunctionInReactiveModel:
active: true
baseClasses: [ 'ReactiveModel' ]baseClasses holds simple names of the base classes of reactive models. The value above is the default.
Not active by default. Needs type resolution.
An intent which is declared and sent by the screen, but which the machine of the view model does not subscribe to, does nothing: the tap is lost silently.
Non-compliant:
class Intents : ViewIntents() {
val onRefresh = intent(name = "refresh")
val onBack = intent(name = "back")
}
class MainViewModel : ViewModel<ViewState, Intents>() {
// ❌ Intents.onBack is never handled
override fun buildMachine() = machine {
onEach(intent(Intents::onRefresh)) {
action { _, _, _ -> model.fetch.start() }
}
}
}Compliant:
class MainViewModel : ViewModel<ViewState, Intents>() {
// ✅
override fun buildMachine() = machine {
onEach(intent(Intents::onRefresh)) {
action { _, _, _ -> model.fetch.start() }
}
onEach(intent(Intents::onBack)) {
action { _, _, _ -> eventSink.sendEvent(BackRequested) }
}
}
}How it works:
- A class is checked when it calls
machinein its own code and refers to intents asIntents::onRefresh(a qualifiedscreen.Intents::onRefreshtoo). - The intents are the properties initialized with an
intent(...)call, of the referred class and of its superclasses declared in the analyzed sources. Other properties (Intents::title) are not required. - An intent is handled when it is referred to in the class itself, in its superclasses or in the functions they call, directly or through other functions, in whatever file (extension functions included).
- The intents classes to check are the ones the class itself and its superclasses refer to. A helper function which refers to another intents class does not make the view model answer for that class.
There is one finding per class, on the machine name, with all the unhandled intents:
View intents are never handled in the machine of "MainViewModel": Intents.onBack.
Not reported:
- a class without a
machinecall, a nested class of a class with one included - a class with a
machinecall and without anyX::namereference
Limits:
- A view model which handles none of its intents has no reference to start from and is not checked.
- A machine built by a superclass is not checked for the subclass.
- An intent which is handled by a subclass, by an object the machine is passed to, or by a function passed by
reference (
::configure) is reported. - A reference in a base view model makes each subclass with its own
machinecall answer for all intents of that intents class.