A set of Detekt rules to help prevent common errors in projects using Jetpack Compose.
Here are some highlights of rules in this rule set:
-
ReusedModifierInstancefinds usages ofmodifierparameter on non-top-level children of a composable function. This tends to happen during refactorings and often leads to incorrect rendering of a composable -
UnnecessaryEventHandlerParametersuggests hoisting event argument passing (state parameter access and constants) to the upper level which often simplifies individual composable components (reportConstantArguments: falseskips constants) -
ModifierHeightWithTextsuggests usingModifier.heightIn()instead ofModifier.height()on a layouts which haveTextchildren, so that if the text turns out to be long and would wrap, layout will not cut it off -
ComposableEventParameterNamingensures that all event handler parameters of composable functions are named in the same Compose-like style, i.e. they haveonprefix and do not use past tense -
ComposableParametersOrderingsuggests the correct grouping and order of composable functions' parameters, ensures the correct position of theModifierparameter and keeps slots named intrailingSlotNames(defaultcontent) last. Overriding andactualfunctions are not checked.allowTrailingEventHandlers: falsealso reports a required event handler placed after optional parameters,allowTrailingLambdas: falseany required non-composable lambda there -
ModifierDefaultValueensures thatmodifierparameter has a correct default value -
MissingModifierDefaultValuechecks ifmodifierdefault value is specified. Overriding andactualfunctions are skipped. Abstract and open functions and functions of interfaces are skipped too, unlesscheckAbstractFunctions: trueis set: the Compose compiler accepts default values in abstract composables only from Kotlin language version 2.1 and in open ones from 2.2 (K2 compiler) -
PublicComposablePreviewfinds and reports composable previews which are not marked asprivate -
TopLevelComposableFunctionsensures that all composable functions are top-level functions (disabled by default;allowInObjects: truealso allows them insideobjects,allowInInterfaces: trueinsideinterfaces) -
ComposableFunctionNameensures that Composable functions which return Unit should start with upper-case while the ones that return a value should start with lower case -
UnnecessaryLayoutWrapperfinds aBox,ColumnorRowwithout parameters which only wraps a singleBox,ColumnorRow, so the child can usually be used directly (disabled by default) -
StateReadCouldBeLoweredfinds avalholding a state read (.valueof aStateor.currentof aCompositionLocal) which is only usedminDepth(default 2) or more composable lambdas deeper, so the state can be read closer to its use. Every composable lambda parameter counts (content,topBar, ...), except the ones of inline composables likeBox,ColumnandRow: an inlined lambda is no recomposition scope of its own. Acrossinlinelambda, like theitemContentof the lazy listitems, does count (disabled by default, requires type resolution) -
NonImmutableDataClassParameterfinds a composable parameter whose type, or one of its type arguments (List<Profile>), is a data class not marked with@Immutableor@Stable. With strong skipping (the default since Kotlin 2.0.20) such a composable is still skippable, but the parameter is compared by instance (===) instead ofequals(), so an equal copy of the data class recomposes it. Not reported: data classes of thekotlinpackage, data classes of libraries which the Compose compiler knows to be stable at compile time (@StabilityInferred),ignoredPackageSegmentsandstableTypePatterns.stableTypePatternstakes the lines of the Compose stability configuration file, comment lines included; a line which the Compose compiler would reject fails the run. Limits: a library data class which holds a class of another file or module is still reported, the Compose compiler decides on its stability only at runtime, list it instableTypePatterns; a pattern is not matched against the supertypes of a class; only data classes are judged, so an unstableList, Java collection or extension receiver is not reported, and aList<Profile>parameter stays unstable for the Compose compiler even whenProfileis annotated (disabled by default, requires type resolution) -
PartiallyUsedViewStatefinds a composable which takes a whole view state (a class matchingstateClassPattern) but reads fewer thanusedFieldsThreshold(default 3) of its properties, such a composable should take the properties instead. Only public and internal properties are counted. Reads insidewith(state) {},state.run {}andstate.apply {}, through a destructuring declaration and of inherited properties are counted;state.let {}andstate.also {}pass the state on, a composable which reads the state only through them is not reported (disabled by default, requires type resolution) -
UnwrappedValueClassImageModelfinds a value class passed as is to themodelof a Coil image function or to thedataof anImageRequestbuilder: it compiles because the parameter isAny?, but Coil can't load an image from a boxed value class, pass its.valueinstead. Value classes of thekotlinpackage (UInt,Result) are not reported (disabled by default, requires type resolution) -
UnnecessaryModifierArgumentfinds aModifierpassed to a parameter which already hasModifieras its default value (Text("Hello", modifier = Modifier)), the argument can be removed. Only functions declared in the analyzed sources are checked, the default value of a library function is not available. A positional argument followed by another positional one can't be removed alone, pass the following arguments by name then:Card("Title", Modifier, false)becomesCard("Title", enabled = false). The rule does not check whether the call without the argument resolves to another overload, suppress the finding there with@Suppress("UnnecessaryModifierArgument")(disabled by default, requires type resolution) -
and others...
Rules can be individually turned on or off in the configuration file.
More detailed rule descriptions with code snippets can be found in the Wiki.
Some rules will only work if detekt is running in a type resolution mode, so make sure it is configured for your build if you want to make full use of them.
Add detekt rules plugin in your build.gradle (or use any other supported method).
Pick the artifact that matches your detekt version:
dependencies {
// detekt 1.22.0 - 1.23.8
detektPlugins("ru.kode:detekt-rules-compose:2.0.0")
// detekt 2.0.0-alpha.6
detektPlugins("ru.kode:detekt-rules-compose-detekt2:2.0.0")
}
Both artifacts contain the same rules with the same ids and configuration keys, so detekt-config.yml does not change
when you switch engines. On detekt 2 the type-resolution rules only run with --analysis-mode full.
Then add this configuration section to your detekt-config.yml to activate the rules:
compose:
ReusedModifierInstance:
active: true
UnnecessaryEventHandlerParameter:
active: true
reportConstantArguments: true
ComposableEventParameterNaming:
active: true
ComposableParametersOrdering:
active: true
trailingSlotNames: [ 'content' ]
allowTrailingEventHandlers: true
allowTrailingLambdas: true
ModifierHeightWithText:
active: true
MissingModifierDefaultValue:
active: true
checkAbstractFunctions: false
PublicComposablePreview:
active: true
TopLevelComposableFunctions:
active: true
allowInObjects: false
allowInInterfaces: false
ComposableFunctionName:
active: true
ConditionCouldBeLifted:
active: true
ignoreCallsWithArgumentNames: [ 'modifier', 'contentAlignment' ]
UnnecessaryLayoutWrapper:
active: true
StateReadCouldBeLowered:
active: true
minDepth: 2
NonImmutableDataClassParameter:
active: true
# data classes of packages with these segments are not reported, for example [ 'schema' ]
ignoredPackageSegments: [ ]
# data classes which are stable without an annotation, in the syntax of the Compose stability configuration file
# (copy its lines here, the rule can't locate the file), for example [ 'com.example.model.**', 'java.time.*' ]
stableTypePatterns: [ ]
PartiallyUsedViewState:
active: true
# regex for the name of a view state class
stateClassPattern: '.*ViewState'
# a state with fewer read properties is reported, classes with fewer properties are not checked
usedFieldsThreshold: 3
UnwrappedValueClassImageModel:
active: true
# functions whose "model" argument is checked
imageFunctions: [ 'AsyncImage', 'SubcomposeAsyncImage', 'rememberAsyncImagePainter' ]
UnnecessaryModifierArgument:
active: true
Detekt manual contains few useful tips on how to configure Detekt in Compose-based projects, check them out!
Maintained by KODE and Contributors ❤️
MIT License
Copyright (c) 2024 KODE LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.