'How to exclude Kotlin files from compiling with Gradle

With Java, we are excluding like this:

java {
    srcDir 'src'
    exclude '**/myTests/**'
}

I want to make the same thing with Kotlin. I am trying to find some documentation on this in official documentation configuring Kotlin, but without any success.

What I've expected and already tried (and of course without any success):

kotlin {
    srcDir 'src'
    exclude '**/myTests/*.kt'
}


Solution 1:[1]

java {
    srcDir 'src'
    exclude '**/myTests/*.kt'
}

There isn't any Kotlin related configuration.

Why I am saying this: I have all the Kotlin files into the kotlin directory and Java files into java directory. But while configuring, I have added:

sourceSets {
   main.java.srcDirs += "src/main/kotlin"
}

This means that with src/main/java, add source files from src/main/kotlin also while compiling.

This should solve your issue.

Solution 2:[2]

Android (likely need improvement, seems flaky):

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile.class).configureEach {
    it.exclude('**/TestExcludeKotlinClass.kt')
}

Solution 3:[3]

If you use a Kotlin Gradle project, try this:

tasks.withType<KotlinCompile> {
exclude("**/packageToExlude/**")}

In my case, a non-Android project.

Solution 4:[4]

I came across a way to make this work specifically for Android unit tests (but I'm assuming it's adaptable) using a combination of other solutions here:

def filesToExclude = [
    '**/*TestOne*.kt',
    '**/*TestTwo*.kt',
    ...
]
tasks.withType(org.gradle.api.tasks.SourceTask.class).configureEach {
  it.exclude(filesToExclude)
}
android.sourceSets.test.kotlin.exclude(filesToExclude)

In my particular case, the extra wildcards around the test name were needed due to other generation occurring (specifically, Dagger with kapt).

This seems to be a bit hacky way to approach it, but it works by ensuring the test target is excluded from all tasks that it could actually be excluded from (including both build & kapt tasks). The sourceSets exclusion is still necessary for the file not to be picked up for compilation (I think this is the Kotlin Gradle Plugin doing it, but it might also be the Android Gradle Plugin).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen
Solution 2 DA_123
Solution 3 Peter Mortensen
Solution 4 Peter Mortensen