Skip to content Skip to sidebar Skip to footer

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. Trying to find some docs on this in offic

Solution 1:

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

There is no Kotlin related configuration.

Why I am saying this, I have all the kotlin files into kotlin directory and java files into java directory. But while configuring, I have put

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:

Android (likely need improvement, seems flaky):

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

Solution 3:

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:

deffilesToExclude = [
    '**/*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 Android Gradle Plugin).

Post a Comment for "How To Exclude Kotlin Files From Compiling With Gradle"