How to get IDEA to detect kotlin generated sources using Gradle

How to get IDEA to detect kotlin generated sources using Gradle

Nish Tahir

So I recently got my hands on Kotlin and it's been great so far.

However one of the things that the IDEA kotlin plugin doesn't do1 is detect the kapt folder which contains any sources generated from annotation processing. This can be fixed using the IDEA gradle plugin2.

The idea plugin isn't able to mark the kapt folder as a source directory unless it's been added to the gradle source set.

sourceSets.main.java.srcDir file("$buildDir/generated/source/kapt/")

The next step is to tell the idea plugin to mark the kapt folder as a generated sources root in the module3.

idea {  
    module {
        // Tell idea to mark the folder as generated sources
        generatedSourceDirs += file("$buildDir/generated/source/kapt/")
    }
}

When put together your build script should look a little like this.

apply plugin: 'idea'

...

kapt {  
    generateStubs = true
}

// Add kapt directory to sources
sourceSets.main.java.srcDir file("$buildDir/generated/source/kapt/")

idea {  
    module {
// Tell idea to mark the folder as generated sources
        generatedSourceDirs += file("$buildDir/generated/source/kapt/")
    }
}
Footnotes and references
  1. →, V. (2015). Better Annotation Processing: Supporting Stubs in kapt. [online] Kotlin Blog. Available at: https://blog.jetbrains.com/kotlin/2015/06/better-annotation-processing-supporting-stubs-in-kapt/#comment-36065 [Accessed 25 Jun. 2016].

  2. Docs.gradle.org. (2016). The IDEA Plugin - Gradle User Guide Version 2.14. [online] Available at: https://docs.gradle.org/current/userguide/idea_plugin.html [Accessed 25 Jun. 2016].

  3. Docs.gradle.org. (2016). IdeaModule - Gradle DSL Version 2.14. [online] Available at: https://docs.gradle.org/current/dsl/org.gradle.plugins.ide.idea.model.IdeaModule.html [Accessed 25 Jun. 2016].