https://kotlinlang.org logo
Join Slack
Powered by
# detekt
  • p

    Peter

    11/14/2024, 12:25 PM
    is there a rule, that prevents
    Pair
    as return type 🤔
    s
    • 2
    • 1
  • e

    Emil Kantis

    11/20/2024, 12:06 PM
    https://detekt.dev/docs/rules/performance/#foreachonrange (and other perf rules) references blog posts that are 7 years old. (Kotlin 1.1) Are they still relevant?
    s
    • 2
    • 4
  • j

    João Silva

    11/21/2024, 5:33 PM
    Hi guys! Do you think it makes sense to skip the
    LongMethod
    rule for
    @Composable
    functions? I've had the need to suppress it multiple times the more I write compose. It can happen because of multiple lambdas, decision making, or any other reason. Do you think it would be a good addition to change the current function to accept a new config like
    ignoredAnnotations
    so that we can configure it? What are your toughts? Thank you!
    b
    • 2
    • 4
  • s

    Sebastian Schuberth

    11/22/2024, 10:58 AM
    Are the detekt tasks with type resolution not cached by Gradle? Even if a single file only changes, all task (even in unrelated projects) seem to be rerun.
    b
    • 2
    • 1
  • g

    GMachine

    11/24/2024, 1:42 PM
    Hello everyone! I’m considering switching from the Detekt Gradle plugin to the CLI in our CI environment to improve performance. Has anyone here had experience with this transition? Would you recommend it? Also, how well does the CLI handle type resolution?
    b
    • 2
    • 1
  • a

    Antonis Radz

    11/26/2024, 4:42 PM
    hey, I know this question was asked many times, but I can not still find clear answer. How to properly setup Detekt for KMP project? Currently I did in project `build.gradle.kts`:
    Copy code
    tasks.withType<io.gitlab.arturbosch.detekt.Detekt> detekt@{
        config.setFrom(files("$rootDir/detekt-config.yml"))
        baseline.set(file("$rootDir/detekt-baseline.xml"))
        setSource(files(rootDir))
        include("**/*.kt")
        exclude("**/*.kts")
        exclude("**/resources/**")
        exclude("**/build/**")
    }
    But this seems to be really slow, on CI it runs around 20mins, and project isn't big. Any ideas? Before CI was running around 5mins
  • g

    GMachine

    11/27/2024, 2:55 PM
    Hi everyone! 👋 I've set up Detekt with type resolution via CLI for our Android project, but I'm encountering some false positives. For example, in the snippet below, Detekt flags
    productArgs.favoriteLink!!.id
    as
    UnnecessaryNotNullOperator
    , even though
    productArgs.favoriteLink
    is in another module and cannot be smart casted (Android Studio confirms this).
    if (productArgs.favoriteLink != null) {
    println(productArgs.favoriteLink!!.id) // Reported as UnnecessaryNotNullOperator
    println(productArgs.favoriteLink.id)  // Compiler error: smart cast not possible
    }
    Here’s how I resolve my classpath using a Gradle task:
    tasks.register("resolveClasspath") {
    def resolvedClasspath = providers.provider {
    def classpathFiles = files()
    // Iterate over application variants during the configuration phase
    android.applicationVariants.all { variant ->
    classpathFiles += variant.javaCompileProvider.get().classpath.filter { it.exists() }
    }
    // Convert classpath to a comma-separated string for later use
    classpathFiles.files.collect { it.absolutePath }.join(",")
    }
    doLast {
    println(resolvedClasspath.get())
    }
    }
    Any ideas why Detekt might generate false positives in this setup? Am I missing something in my configuration? 🤔
    b
    • 2
    • 4
  • e

    eygraber

    11/27/2024, 8:21 PM
    Once type resolution is working for non jvm targets, would that work on any host like publishing from any host, or would that target's detekt task have to be run on a native host (e.g. ios on a mac)?
  • a

    arve

    12/02/2024, 1:46 PM
    Is there a way to get project statistics and complexity report in console with CLI, without first generating and modifying a
    detekt.yaml
    ? (or even better, to the txt report)
    b
    • 2
    • 1
  • h

    hfhbd

    12/03/2024, 8:18 AM
    Currently, the report configuration on the detekt extension is deprecated and you should configure the tasks directly. But looking forward regarding dcl, I would still prefer configuring it in the extension and remove direct task configuration. Are you open to discuss it?
  • l

    Louis

    12/04/2024, 5:35 PM
    Hello 👋 I want to setup detekt on a project with 400 modules and run it using a git hook on staged files only. So I used detekt cli, which works well except for rules using type resolution. The only way I've found is to use the gradle plugin. But unless I'm mistaken, I have to run it on every sub projects, which takes a long time. detekt cli was much faster and allows me to specify only a few files. I'd like to get close to detekt-cli performance with rules that use type resolution. I've also tried making a gradle task (detektAll) but it's the same as cli, the classpaths are missing. How can I speed up the task ? Or how can I retrieve relevant classpaths for detekt cli ? 🙂 Here is my configuration with gradle plugin:
    Copy code
    subprojects {
     apply {
      plugin("io.gitlab.arturbosch.detekt")
     }
    
     detekt {
      source.setFrom("src/main/kotlin", "src/main/java")
    
      buildUponDefaultConfig = true
      config.setFrom("$rootDir/detekt/config.yml")
      baseline = file("$projectDir/detekt/baseline.xml")
      autoCorrect = true
      parallel = true
      ignoreFailures = false
      buildUponDefaultConfig = true
      autoCorrect = true
      ignoredBuildTypes = ["release", "benchmarkDebug", "benchmarkRelease"]
      basePath = rootDir
     }
    
     dependencies {
      detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.7")
      detektPlugins("io.nlopez.compose.rules:detekt:0.4.17")
     }
    }
    âž• 1
    b
    • 2
    • 3
  • e

    Eric

    01/21/2025, 3:25 PM
    is there a rule for multi-line expression bodies? I'm fine with
    fun foo() = "blah"
    but I'd like to enforce that multi-line expression bodies have a line break after the
    =
    or at least have it consistent within a single class/file
    b
    • 2
    • 2
  • l

    Louis

    01/22/2025, 10:11 AM
    Hello, I'm trying to use the detekt plugin on Android studio but unfortunately I have an error on config.yml. However I use the same file with detekt-cli or the gradle plugin and it works fine. Here's the error, do you know why?
    Copy code
    Unexpected error while running detekt analysis
    
    io.gitlab.arturbosch.detekt.api.Config$InvalidConfigurationError: Provided configuration file is invalid: Structure must be from type Map<String,Any>!
    while constructing a mapping
     in reader, line 1, column 1:
        build:
        ^
    found duplicate key formatting
     in reader, line 1056, column 1:
        formatting:
        ^
  • z

    Zsolt.bertalan

    02/13/2025, 9:41 PM
    I saw the discussions on Github about detekt 2.0.0, but it died down somewhat. Is this still in the works?
    g
    • 2
    • 1
  • c

    Czerwinskimarek88

    02/14/2025, 8:56 AM
    Hi everyone 👋 I want to configure detekt so that the MaximumLineLength rule still blocks long lines, but makes an exception for logging code, such as:
    Copy code
    <http://logger.info|logger.info> { "This is a very long logging message that exceeds the character limit, but I want Detekt to ignore it." }
    I’ve tried various approaches, but I couldn’t find an in-built option to ignore specific function calls (like
    <http://logger.info|logger.info>
    ,
    logger.debug
    ,
    logger.warn
    ). Is there a way to achieve this? Maybe there's a configuration option or a custom rule I could create? Thanks in advance for your help! 🚀
  • b

    Brian Hartvigsen

    02/21/2025, 6:53 PM
    Can someone help me understand why the
    MissingUseCall
    rule detects the following as not using
    use
    ?
    Copy code
    val code = """
                fun <T> MyCloseable.useMe(block: (object) -> T) = use { block(this) }
                fun MyCloseable.useMe() = use {}
    
    
    
                fun test() {
                    MyCloseable(0).use {}
                    MyCloseable(1).useMe()
                    MyCloseable(2).useMe { it.doStuff() }
                }
    
                ${myClosable(clazz)}
            """.trimIndent()
    These are obviously contrived, we have a pattern that would look more like:
    Copy code
    MyCloseable(0).use { it.subPropertyClosable.use { sub -> sub.doStuff() } }
    I was trying to shorthand that to something like the
    useMe
    block except it's more like
    fun <T> MyCloseable.useMe(block: () -> T ) = use { subPropertyCloseable.use { block() } }
    , but I get an error that
    MyCloseable
    is doesn't call
    use
    to access the
    Closeable
    .
  • k

    Kim

    02/24/2025, 3:48 AM
    Is pre-commit framework support planned for detekt? Of course I could write a local script and link via
    repo: local
    as in the guides but would be nice to have some sensible default hooks support with
    .pre-commit-hooks.yaml
    at the repo top level.
    g
    • 2
    • 3
  • e

    eygraber

    03/05/2025, 11:49 PM
    Is it possible to exclude a specific
    ForbiddenMethodCall
    value for tests instead of the whole rule?
    g
    • 2
    • 2
  • m

    Max

    03/21/2025, 3:44 PM
    Hey! I'm trying to use type resolution for my custom rule. I saw, that I should annotate the rule by
    @RequiresFullAnalysis
    , but I don't see it in api. I use
    1.23.8
    version. Has something changed? How can I use it?
    b
    • 2
    • 2
  • d

    David Glasser

    03/26/2025, 10:11 PM
    Hi. We're just getting started with Detekt and have set it up with Gradle integration, including a custom plugin that is built within our repo. Is the IntelliJ plugin supposed to support this sort of setup? I installed it but it doesn't seem to be detecting any issues.
    • 1
    • 1
  • d

    Doug McCluer

    03/31/2025, 3:14 PM
    Can I write a rule that will report usages of Context Receivers? ex:
    Copy code
    context(Activity)
    fun finishWithContextReceiver(){
        finish()
    }
    b
    • 2
    • 2
  • h

    HÃ¥kon Pettersen

    04/04/2025, 4:21 AM
    I'm trying to add a rule to forbid the use of
    @Suppress("all")
    like this:
    Copy code
    ForbiddenSuppress:
      active: true
      rules: ["all", "CyclomaticComplexMethod"]
    Currently,
    @Suppress("all")
    isn't being caught, whereas
    "CyclomaticComplexMethod"
    works as expected. Has anyone encountered this issue? docs: https://detekt.dev/docs/rules/style/#forbiddensuppress
    s
    • 2
    • 7
  • m

    maarten ha

    05/02/2025, 12:03 PM
    How can I setup Detekt with ktlint correctly that when I use the reformat shortcut in Intelij it formats to the Detekt configuration? Both Detekt and ktlint plugins are installed in my IDE. Current gradle configuration
    Copy code
    tasks {
        withType<io.gitlab.arturbosch.detekt.Detekt> {
            parallel = true
            config.setFrom(files("/config/detekt/detekt.yml"))
            buildUponDefaultConfig = true
            jvmTarget = "$projectJvmTarget"
            autoCorrect = true
    
            setSource(files("src/main/kotlin", "src/test/kotlin"))
            setOf(
                "**/*.kt",
                "**/*.kts",
                ".*/resources/.*",
                ".*/build/.*",
                "/versions.gradle.kts",
            ).forEach {
                include(it)
            }
    
            reports {
                html.required.set(true)
                html.outputLocation.set(file("reports/detekt/detekt.html"))
    
                sarif.required.set(true)
                sarif.outputLocation.set(file("reports/detekt/detekt.sarif"))
            }
    
            outputs.dir("reports/detekt/")
        }
    }
    
    dependencies {
    ...
     detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.8")
    }
    For the detekt config I just ran the generate config task. Have not changed anything in it
    s
    d
    • 3
    • 2
  • h

    hfhbd

    05/15/2025, 8:29 AM
    Does Detekt support processing files with 2.2.0-Beta2 and enabled context parameters?
    b
    • 2
    • 1
  • o

    Oleksandr Balan

    06/11/2025, 10:08 AM
    Hey 👋 I would like to set up a custom Gradle task that runs Detekt with type resolution, using a single custom rule. This needs to work in a multi-modular project that includes both JVM and Android library modules. I'm currently struggling with setting up the correct classpath (I've read it can be tricky). Has anyone dealt with a similar setup and can share how they configured it? Thanks for any advice.
    x
    • 2
    • 3
  • e

    Ernestas

    06/19/2025, 5:48 AM
    Hey, as I understand the detekt plugin is not able to show live warnings for rules that require type resolution. I would still like those rules to be checked during development, is there a way to configure all rules to run on each build? I tried creating a task dependency, but
    build.gradle
    does not see the task -
    detektMain
    , only -
    detekt
    is available. I can still run the
    detektMain
    task manually without problems though.
  • m

    Maxime Michel

    07/09/2025, 11:46 AM
    Hey guys, I have a very very specific issue with Detekt currently and I'm wondering if any eagle-eyed amongst you would be able to help me identify the source of the problem and hopefully a possible fix ^^ I'm currently working on a KMP project and this project uses Compose Multiplatform (CMP). I have also set up convention plugins to help centralise the behaviour of each module. Here is a global overview of the project structure omitting anything that doesn't help understand the issue.
    Copy code
    my-project:
    -> android
       |-> androidApp (Android application module)
       |-> other android specific modules
    -> build-logic
       |-> convention
           |-> Detekt.kt (Detekt specific configurations are contained here)
           |-> MultiplatformLibraryConventionPlugin.kt
    -> ios (iOS application)
    -> kmp
       |-> data
       |-> domain
       |-> presentation
    -> testing
       |-> detekt
       |-> konsist
    This is a somewhat generic KMP project structure I think (but this works without issues so I'm not planning on changing this structure). The contents of the
    :testing:detekt
    module is attached as an image. I followed the documentation and updated my
    Detekt.kt
    file to apply (or so I thought) the new rule I created:
    Copy code
    internal fun Project.configureDetekt() {
        configure<DetektExtension> {
            source.from(files("$projectDir/src"))
            config.from(files(
                "$rootDir/config/quality/detekt/detekt-config.yml",
                "$rootDir/testing/detekt/src/main/resources/config/config.yml",
            ))
            baseline = file("$rootDir/config/quality/detekt/baseline.xml")
            autoCorrect = true
        }
    
        tasks.withType<Detekt> {
            exclude("**/test/")
            exclude(".*/tmp/.*")
            dependsOn(":testing:detekt:assemble")
        }
    
        dependencies {
            CONFIGURATION_DETEKT_PLUGINS(libs.findLibrary("detekt.cli").get())
            CONFIGURATION_DETEKT_PLUGINS(libs.findLibrary("detekt.formatting").get())
            CONFIGURATION_DETEKT_PLUGINS(libs.findLibrary("detekt.libraries").get())
            CONFIGURATION_DETEKT_PLUGINS(project(":testing:detekt"))
        }
    }
    In my custom rule, I added an override for the
    visitKtFile
    function that simply prints the file name but this does nothing and I see no logs when running the detekt task.
    • 1
    • 1
  • v

    Vanessa Johnson

    07/14/2025, 1:19 PM
    Hi, I have a PR up with some work to integrate the new problems api as a part of GSOC and any feedback would be appreciated! Thanks. The link will be in 🧵
    • 1
    • 1
  • e

    Eugen Martynov

    07/14/2025, 2:02 PM
    Does detekt have for body expression functions that return Unit and have no explicit return type specification?
    ✅ 1
    b
    • 2
    • 11
  • a

    Aditya Bhaskar

    07/14/2025, 5:17 PM
    Hey folks, I'm updating our projects to Kotlin 2.2.0 and detekt appears to be fairly incompatible. I'm getting lots of false
    UnusedPrivateMember
    and
    NullableToStringCall
    errors, and a few ISEs:
    Copy code
    > A failure occurred while executing io.gitlab.arturbosch.detekt.invoke.DetektWorkAction
       > java.lang.IllegalStateException: Analyzing something.kt led to an exception.
         Location: java.base/java.util.concurrent.CompletableFuture.encodeThrowable(Unknown Source)
         The original exception message was: java.lang.NullPointerException
         Running detekt '1.23.8' on Java '21.0.6+-13391695-b895.109' on OS 'Mac OS X'
         If the exception message does not help, please feel free to create an issue on our GitHub page.
    Given this PR is still draft, is this to be expected?
    b
    g
    • 3
    • 11