Dmytro Serdiuk
10/01/2023, 12:34 PMAlexander.Likhachev
10/07/2023, 12:24 AMAnton Lakotka [JB]
10/07/2023, 6:53 AMplugins {
`java-library`
// OR
// kotlin("jvm")
}
sourceSets {
main { } // default source set for main code
test { } // default source set for test code
create("custom") { } // your custom source set
}
Gradle java plugin compiles source sets independently. i.e. for source code from main
will be compiled independently from test
or custom
and vice versa.
for test
source set there is a little exception: it depends on main
compilation results (classes + resources).
Because code compiles independently you can, for example, configure compiler options or declare different dependencies.
For example this is how you can add custom dependency to your custom source set:
dependencies {
// adds dependency to main source set
api("foo:bar:1.0")
// adds dependency to custom source set
val customApi = sourceSets.getByName("custom").apiConfigurationName
configurations.maybeCreate(customApi)
add(customApi, "foo:baz:2.0")
}
And custom
will be compiled with foo:baz:2.0
dependency.
You can read more about custom source sets on Gradle Documentation page: https://docs.gradle.org/current/javadoc/org/gradle/api/tasks/SourceSet.html ; https://docs.gradle.org/current/userguide/building_java_projects.html#sec:java_source_sets
In Kotlin Multiplatform Gradle Plugin term "source set" has different meaning than in Gradle Java Plugin. I'm not going to explain all the reasons here.
But Kotlin Multiplatform has a concept of "Compilation" this compilation in practice has similar API as Gradle Source Set and does similar job: configures independent source code compilations.
Imagine if you want to migrate sample jvm project I mentioned above to koltin multiplatform, then you would need to do following:
plugins {
kotlin("multiplatform")
}
kotlin {
jvm {
compilations {
val main by getting { } // get default main compilation
val test by getting { } // get default test compilation
val custom by creating { } // create custom compilation
}
}
}
And if you want to add dependencies like in the sample then you can do following:
compilations {
val main by getting {
dependencies {
api("foo:bar:1.0")
}
}
val test by getting { }
val custom by creating {
dependencies {
api("foo:baz:2.0")
}
}
}
You might noticed that Java Source Set had an api to get apiConfigurationName
to which dependency was added. You can do the same with Kotlin Compilations:
kotlin {
jvm {
compilations.getByName("custom").apiConfigurationName // you can add dependencies to this configuration as well
}
}
I hope I answered your question.Dmytro Serdiuk
10/07/2023, 3:09 PM