Top Related Projects
Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard. By default it supports the Google Java Style Guide and Sun Code Conventions, but is highly configurable. It can be invoked with an ANT task and a command line program.
SpotBugs is FindBugs' successor. A tool for static analysis to look for bugs in Java code.
An extensible multilanguage static code analyzer.
Continuous Inspection
A static analyzer for Java, C, C++, and Objective-C
Catch common Java mistakes as compile-time errors
Quick Overview
Detekt is a static code analysis tool for Kotlin. It operates on the abstract syntax tree provided by the Kotlin compiler, allowing it to detect code smells, complexity issues, and potential bugs in Kotlin projects. Detekt is highly configurable and can be integrated into various build tools and CI pipelines.
Pros
- Extensive rule set covering a wide range of code quality issues
- Highly customizable with the ability to enable/disable rules and set thresholds
- Integrates well with popular build tools like Gradle and Maven
- Supports custom rule creation for project-specific requirements
Cons
- Can produce false positives, requiring careful configuration
- May slow down build times, especially on larger projects
- Learning curve for configuring and customizing rules effectively
- Some rules may be overly strict for certain coding styles or preferences
Code Examples
- Basic Gradle setup:
plugins {
id("io.gitlab.arturbosch.detekt").version("1.22.0")
}
detekt {
buildUponDefaultConfig = true
allRules = false
config = files("$projectDir/config/detekt.yml")
}
- Custom rule implementation:
class CustomRule : Rule() {
override val issue = Issue(
javaClass.simpleName,
Severity.Style,
"This is a custom rule",
Debt.FIVE_MINS
)
override fun visitNamedFunction(function: KtNamedFunction) {
super.visitNamedFunction(function)
if (function.name?.startsWith("test") == true) {
report(CodeSmell(issue, Entity.from(function), "Function names should not start with 'test'"))
}
}
}
- Configuring rules in YAML:
complexity:
TooManyFunctions:
thresholdInFiles: 15
thresholdInClasses: 15
thresholdInInterfaces: 15
thresholdInObjects: 15
thresholdInEnums: 15
LongParameterList:
functionThreshold: 6
constructorThreshold: 7
ignoreDefaultParameters: true
Getting Started
To get started with Detekt in a Gradle project:
- Add the Detekt plugin to your
build.gradle.kts
:
plugins {
id("io.gitlab.arturbosch.detekt").version("1.22.0")
}
- Configure Detekt in your
build.gradle.kts
:
detekt {
buildUponDefaultConfig = true
allRules = false
config = files("$projectDir/config/detekt.yml")
baseline = file("$projectDir/config/baseline.xml")
}
-
Create a
detekt.yml
configuration file in theconfig
directory to customize rules. -
Run Detekt with:
./gradlew detekt
Competitor Comparisons
Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard. By default it supports the Google Java Style Guide and Sun Code Conventions, but is highly configurable. It can be invoked with an ANT task and a command line program.
Pros of Checkstyle
- Mature and widely adopted tool with extensive documentation
- Supports a broader range of programming languages beyond Java
- Highly configurable with a large set of built-in checks
Cons of Checkstyle
- Steeper learning curve due to XML-based configuration
- Less focus on performance and code smell detection compared to Detekt
- Limited support for modern Java features and idioms
Code Comparison
Checkstyle configuration (XML):
<module name="Checker">
<module name="TreeWalker">
<module name="MethodLength">
<property name="max" value="50"/>
</module>
</module>
</module>
Detekt configuration (YAML):
complexity:
LongMethod:
threshold: 50
Both tools aim to improve code quality, but they differ in their approach and target languages. Checkstyle is more established and versatile, while Detekt is tailored for Kotlin and offers a more modern, performance-oriented approach. Checkstyle's XML configuration can be more verbose, whereas Detekt's YAML configuration is generally more concise and easier to read. Detekt also provides better integration with Kotlin-specific features and static analysis capabilities.
SpotBugs is FindBugs' successor. A tool for static analysis to look for bugs in Java code.
Pros of SpotBugs
- Supports multiple JVM languages (Java, Scala, Groovy)
- Extensive bug pattern database with over 400 bug patterns
- Integration with popular build tools and IDEs
Cons of SpotBugs
- Slower analysis compared to Detekt
- Less focus on code style and formatting issues
- Steeper learning curve for customizing and extending
Code Comparison
SpotBugs (XML configuration):
<FindBugsFilter>
<Match>
<Bug pattern="NP_NONNULL_RETURN_VIOLATION"/>
</Match>
</FindBugsFilter>
Detekt (YAML configuration):
complexity:
TooManyFunctions:
thresholdInFiles: 11
thresholdInClasses: 11
thresholdInInterfaces: 11
Key Differences
- SpotBugs is primarily focused on finding bugs and potential issues in Java bytecode, while Detekt is specifically designed for Kotlin static code analysis.
- Detekt offers more extensive code style and formatting checks, making it better suited for maintaining consistent coding standards in Kotlin projects.
- SpotBugs has a longer history and a larger community, resulting in a more comprehensive bug pattern database.
- Detekt's configuration is more user-friendly and easier to customize, using YAML format instead of XML.
Both tools are valuable for improving code quality, with SpotBugs excelling in bug detection across JVM languages and Detekt providing specialized analysis for Kotlin projects.
An extensible multilanguage static code analyzer.
Pros of PMD
- Supports multiple programming languages (Java, JavaScript, Apex, PL/SQL, etc.)
- Extensive rule set covering a wide range of code quality issues
- Highly customizable with XML-based rule configuration
Cons of PMD
- Steeper learning curve due to its multi-language support and complex configuration
- Can be slower for large codebases compared to language-specific tools
- Less focused on Kotlin-specific issues and best practices
Code Comparison
PMD (Java):
<rule ref="category/java/bestpractices.xml/UnusedPrivateMethod"/>
<rule ref="category/java/codestyle.xml/UnnecessaryFullyQualifiedName"/>
<rule ref="category/java/errorprone.xml/EmptyCatchBlock"/>
Detekt (Kotlin):
complexity:
LongMethod:
threshold: 60
TooManyFunctions:
thresholdInFiles: 11
style:
MagicNumber:
ignoreNumbers: ['-1', '0', '1', '2']
Both tools allow for customizable rule configurations, but Detekt's YAML-based config is more concise and Kotlin-focused, while PMD's XML-based config offers broader language support.
Continuous Inspection
Pros of SonarQube
- Multi-language support: Analyzes code in 27+ programming languages
- Comprehensive analysis: Covers code quality, security vulnerabilities, and technical debt
- Integration with CI/CD pipelines and popular development tools
Cons of SonarQube
- Resource-intensive: Requires significant server resources for large projects
- Steeper learning curve: More complex setup and configuration process
- Commercial licensing for advanced features
Code Comparison
SonarQube (Java):
@Rule(key = "S1234")
public class MyCustomRule extends BaseTreeVisitor implements JavaFileScanner {
private JavaFileScannerContext context;
@Override
public void scanFile(JavaFileScannerContext context) {
this.context = context;
scan(context.getTree());
}
}
Detekt (Kotlin):
class MyCustomRule : Rule() {
override val issue = Issue(
javaClass.simpleName,
Severity.Warning,
"Description of the issue",
Debt.FIVE_MINS
)
override fun visitNamedFunction(function: KtNamedFunction) {
super.visitNamedFunction(function)
// Custom logic here
}
}
SonarQube offers a more comprehensive solution for multi-language projects with extensive integrations, while Detekt provides a lightweight, Kotlin-specific static code analysis tool with easier setup and configuration.
A static analyzer for Java, C, C++, and Objective-C
Pros of Infer
- Supports multiple languages (C, C++, Objective-C, Java)
- More advanced static analysis capabilities, including interprocedural analysis
- Backed by Facebook, with extensive use in large-scale projects
Cons of Infer
- Steeper learning curve and more complex setup
- Slower analysis compared to Detekt
- Less focused on Kotlin-specific issues and best practices
Code Comparison
Detekt configuration example:
detekt {
config = files("path/to/config.yml")
buildUponDefaultConfig = true
allRules = false
}
Infer command-line usage:
infer run -- javac MyFile.java
infer run -- gradle build
Both tools aim to improve code quality through static analysis, but they differ in scope and focus. Detekt is tailored for Kotlin projects, offering quick and easy integration with a focus on Kotlin-specific issues. Infer, on the other hand, provides more advanced analysis across multiple languages, making it suitable for larger, multi-language projects at the cost of increased complexity and setup time.
Catch common Java mistakes as compile-time errors
Pros of Error-prone
- Broader language support: Works with Java, Android, and J2ObjC
- Integrated with Java compiler, catching issues at compile-time
- Extensive set of built-in checks and customizable rules
Cons of Error-prone
- Limited to Java ecosystem, while Detekt supports Kotlin
- Steeper learning curve for configuration and custom rule creation
- Less focus on code style and formatting compared to Detekt
Code Comparison
Error-prone example:
@Nullable
public String getName() {
return null;
}
Detekt example:
fun getName(): String? {
return null
}
Both tools would flag these functions for potentially returning null values, but Detekt's analysis is specific to Kotlin's null safety features.
Key Differences
- Language focus: Error-prone targets Java, while Detekt is designed for Kotlin
- Integration: Error-prone works at compile-time, Detekt can be used as a standalone tool
- Customization: Both offer extensibility, but Error-prone has a more complex setup process
- Community: Error-prone has Google's backing, while Detekt has strong community support
Use Cases
- Choose Error-prone for Java projects, especially those using Google's Java style guide
- Opt for Detekt in Kotlin projects, particularly those emphasizing code style and maintainability
Both tools are valuable for improving code quality and catching potential bugs early in the development process.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
detekt
Meet detekt, a static code analysis tool for the Kotlin programming language. Visit the project website for installation guides, rule descriptions, configuration options and more.
Features
- Code smell analysis for your Kotlin projects.
- Highly configurable rule sets.
- Generate baselines to suppress existing issues for legacy projects while making sure no new issues are introduced.
- Suppress issues in source files using
@Suppress
annotations. - Support for different report formats: HTML, Markdown, SARIF, XML (Checkstyle) and custom reports.
- Extend detekt with custom rule sets and reports.
- Complexity reports based on lines of code, cyclomatic complexity and number of code smells.
- First party integration with Gradle with our Gradle plugin.
- A community of third party plugins that adds more rules and features to detekt.
Quick-Links
- Changelog and migration guides
- Available CLI options
- Rule set and rule descriptions
- Writing custom rules and extending detekt
- Suppressing issues in code
- Suppressing issues via baseline file
- Configuring detekt
- Sample Gradle integrations examples:
Quick Start ...
with the command-line interface
curl -sSLO https://github.com/detekt/detekt/releases/download/v[version]/detekt-cli-[version]-all.jar
java -jar detekt-cli-[version]-all.jar --help
You can find other ways to install detekt here
with Gradle
plugins {
id("io.gitlab.arturbosch.detekt") version "[version]"
}
repositories {
mavenCentral()
}
detekt {
buildUponDefaultConfig = true // preconfigure defaults
allRules = false // activate all available (even unstable) rules.
config.setFrom("$projectDir/config/detekt.yml") // point to your custom config defining rules to run, overwriting default behavior
baseline = file("$projectDir/config/baseline.xml") // a way of suppressing issues before introducing detekt
}
tasks.withType<Detekt>().configureEach {
reports {
html.required.set(true) // observe findings in your browser with structure and code snippets
xml.required.set(true) // checkstyle like format mainly for integrations like Jenkins
sarif.required.set(true) // standardized SARIF format (https://sarifweb.azurewebsites.net/) to support integrations with GitHub Code Scanning
md.required.set(true) // simple Markdown format
}
}
// Groovy DSL
tasks.withType(Detekt).configureEach {
jvmTarget = "1.8"
}
tasks.withType(DetektCreateBaselineTask).configureEach {
jvmTarget = "1.8"
}
// or
// Kotlin DSL
tasks.withType<Detekt>().configureEach {
jvmTarget = "1.8"
}
tasks.withType<DetektCreateBaselineTask>().configureEach {
jvmTarget = "1.8"
}
See maven central for releases and sonatype for snapshots.
If you want to use a SNAPSHOT version, you can find more info on this documentation page.
Requirements
Gradle 6.8.3+ is the minimum requirement. However, the recommended versions together with the other tools recommended versions are:
Detekt Version | Gradle | Kotlin | AGP | Java Target Level | JDK Max Version |
---|---|---|---|---|---|
1.23.7 | 8.10 | 2.0.10 | 8.5.2 | 1.8 | 21 |
The list of recommended versions for previous detekt version is listed here.
Adding more rule sets
detekt itself provides a wrapper over ktlint as the formatting
rule set
which can be easily added to the Gradle configuration:
dependencies {
detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:[version]")
}
Similarly, there are extra rule sets available for detekt from detekt:
dependencies {
detektPlugins("io.gitlab.arturbosch.detekt:detekt-rules-libraries:[version]")
detektPlugins("io.gitlab.arturbosch.detekt:detekt-rules-ruleauthors:[version]")
}
For more info visit the Detekt Marketplace.
Likewise custom extensions can be added to detekt.
Contributing
See CONTRIBUTING
Thanks to all the people who contributed to detekt!
Mentions
As mentioned in...
- To Detekt 2.0, and beyond!
- droidcon London 2021 - Detekt - State of the Union
- KotlinConf 2018 - Safe(r) Kotlin Code - Static Analysis Tools for Kotlin by Marvin Ramin
- droidcon NYC 2018 - Static Code Analysis For Kotlin
- Kotlin on Code Quality Tools - by @vanniktech Slides Presentation
- Integrating detekt in the Workflow
- Check the quality of Kotlin code
- Kotlin Static Analysis Tools
- Are you still smelling it?: A comparative study between Java and Kotlin language by Flauzino et al.
- Preventing software antipatterns with Detekt
Integrations:
- IntelliJ integration
- SonarQube integration
- TCA(Tencent CodeAnalysis) integration
- Codacy
- Gradle plugin that configures Error Prone, Checkstyle, PMD, CPD, Lint, Detekt & Ktlint
- Violations Lib is a Java library for parsing report files like static code analysis.
- sputnik is a free tool for static code review and provides support for detekt
- Detekt Maven plugin that wraps the Detekt CLI
- Detekt Bazel plugin that wraps the Detekt CLI
- Gradle plugin that helps facilitate GitHub PR checking and automatic commenting of violations
- Codefactor
- GitHub Action: Detekt All
- GitHub Action: Setup detekt
Custom rules and reports from 3rd parties can be found on our Detekt Marketplace.
Credits
- JetBrains - Creating IntelliJ + Kotlin
- PMD & Checkstyle & ktlint - Ideas for threshold values and style rules
Top Related Projects
Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard. By default it supports the Google Java Style Guide and Sun Code Conventions, but is highly configurable. It can be invoked with an ANT task and a command line program.
SpotBugs is FindBugs' successor. A tool for static analysis to look for bugs in Java code.
An extensible multilanguage static code analyzer.
Continuous Inspection
A static analyzer for Java, C, C++, and Objective-C
Catch common Java mistakes as compile-time errors
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot