As per the Gradle Kotlin plugin page.
Kotlin sources can be mixed with Java sources in the same folder, or in different folders. The default convention is using different folders. The corresponding sourceSets property should be updated if not using the default convention.
I want to add some Java files in src/main/kotlin and have the compileJava task compile them. I tried to come up with the following block to achive it, but no dice.
java {
val kotlinSrcDir: File = File(projectDir, "src/main/kotlin")
sourceSets["main"].java.srcDirs.add(kotlinSrcDir)
val javasrcdirs: Set<File> = sourceSets["main"].java.srcDirs
println(javasrcdirs)
}
What gives?
java {
val kotlinSrcDir = "src/main/kotlin"
val mainJavaSourceSet: SourceDirectorySet = sourceSets.getByName("main").java
mainJavaSourceSet.srcDir(kotlinSrcDir)
println(mainJavaSourceSet.srcDirs)
}
When you call srcDirs
in your build.gradle.kts
, the actual method called is SourceDirectorySet.getSrcDirs()
. The implementation of this method in DefaultSourceDirectorySet.getSrcDirs()
returns a defensive copy of the collection, and this is why modifying it has no effect.
So to actually add a new source directory to the set use srcDir(Object)
or srcDirs(Object...)
.