Gradle Kotlin DSL and Project Layout

Gradle Kotlin DSL and Project Layout in Kotlin: A joinery workshop that builds cabinets for larger kitchen installations works from a bill of materials: a…

The Analogy: The Cabinet Workshop's Bill of Materials

A joinery workshop that builds cabinets for larger kitchen installations works from a bill of materials: a written list of the timber, the fittings, and the subassemblies that go into each cabinet, which suppliers they come from, and which jigs and tools are needed to build it. A Gradle build script written in the Kotlin DSL -- build.gradle.kts -- is that bill of materials for a software module. Its plugins block names the tools, its repositories block names the suppliers, and its dependencies block lists the parts. Because it is Kotlin, not a separate language, you get type checking and IDE completion while writing the build itself.

The subtle part is how each part is classified, because a cabinet is not the end of the line -- a kitchen fitter installs it into something larger. Some fittings are exposed at the cabinet's mounting face: the standard bracket the fitter bolts onto is part of the published interface, so the fitter must know about it. Other fittings are strictly internal: the glue, the dowels, the particular brand of concealed hinge, which the fitter neither sees nor should ever depend on. Gradle draws exactly this line with dependency configurations. An api dependency is exposed at the mounting face, visible to everyone who installs your module; an implementation dependency is internal, used to build your module but hidden from its consumers.

Other classifications refine this further, matching parts to when they are needed. Some parts are used only during the workshop's own bench testing and never ship in the product -- that is testImplementation. Some are needed only while cutting and shaping but are not part of the finished piece -- compileOnly. Some appear only during final assembly on site -- runtimeOnly. And to keep every workshop ordering identical parts, the firm maintains a master parts list with agreed catalogue numbers, which is Gradle's version catalog: a single libs.versions.toml that every module references so versions never drift apart. The standard bench layout -- main stock in src/main/kotlin, the QA bench in src/test/kotlin, and several coordinated workshops for a big job -- is the conventional project structure.

The failure that forces a costly refit is publishing an internal fitting as though it were an exposed one -- declaring api where implementation was meant. Now every downstream installation inherits a dependency on your private concealed-hinge brand: their build classpath is polluted with a part they were never supposed to see, and worse, some of them start relying on it. The day you swap that internal hinge for a better one, every consumer that leaned on the leaked part breaks and must be refitted. The mirror failure is hiding a fitting that genuinely belongs on the mounting face -- using implementation where api was needed -- so a consumer cannot see a type your public method actually returns, and their code will not compile until you promote it. The craft is to expose exactly the parts that form your interface and conceal everything else.


Syntax or Core Structure

A build.gradle.kts declares plugins, repositories, and dependencies in typed Kotlin. The shape is illustrative (Gradle runs it, not main):

plugins {
    kotlin("jvm") version "1.9.0"
}

repositories {
    mavenCentral()
}

dependencies {
    api("com.example:public-model:1.2.0")          // exposed to consumers
    implementation("com.example:internal-json:2.0") // hidden from consumers
    testImplementation(kotlin("test"))              // test-only
}

The consumer-visibility rule those configurations encode is pure logic and can be modelled deterministically: a downstream module sees only the api dependencies of a library it depends on, never the implementation ones.

data class Dep(val name: String, val api: Boolean)

fun consumerClasspath(libName: String, deps: List<Dep>): List<String> =
    listOf(libName) + deps.filter { it.api }.map { it.name }

fun main() {
    val deps = listOf(
        Dep("public-model", api = true),
        Dep("internal-json", api = false)
    )
    println(consumerClasspath("my-lib", deps))
}

Output:

[my-lib, public-model]

A consumer that depends on "my-lib" gets "my-lib" itself plus its api dependencies -- here "public-model" -- on its compile classpath. The implementation dependency "internal-json" is filtered out, so the consumer cannot see or use it. This is precisely Gradle's behaviour: api dependencies leak transitively to consumers, implementation dependencies stay private to the module that declares them. Choosing between the two decides what your module's public build surface is.


Technical Depth: Configurations, Catalogs, and Tasks

The dependency configurations

Each configuration says both when a dependency is needed and whether consumers can see it. The table lists the common ones.

ConfigurationAvailable atVisible to consumers?
apicompile and runtimeyes (leaks transitively)
implementationcompile and runtimeno (hidden)
compileOnlycompile onlyno
runtimeOnlyruntime onlyno
testImplementationtest compile and runtimetest only

The default choice for most dependencies should be implementation, reserving api for the few whose types genuinely appear in your module's public signatures.

Version catalogs centralise versions

A version catalog (libs.versions.toml) gives each library a single alias and version, so every module resolves to the same coordinates. The resolution is a simple lookup:

val catalog = mapOf(
    "coroutines" to "1.7.3",
    "serialization" to "1.6.0"
)

fun resolve(alias: String): String =
    catalog[alias] ?: error("unknown library: " + alias)

fun main() {
    println("coroutines -> " + resolve("coroutines"))
    println("serialization -> " + resolve("serialization"))
}

Output:

coroutines -> 1.7.3
serialization -> 1.6.0

Each alias maps to exactly one version, looked up directly by key, so resolve("coroutines") yields "1.7.3" and resolve("serialization") yields "1.6.0". An unknown alias hits the error(...) and fails loudly rather than silently picking a wrong version. A real catalog does the same across every module, which is how a large build keeps one library on one version instead of a tangle of subtly different ones.

Tasks run in dependency order

Gradle tasks form a graph via dependsOn, and Gradle runs prerequisites first. A linear chain -- compile before test before jar -- executes in that order:

fun main() {
    // compile -> test -> jar, each dependsOn the previous
    val plan = listOf("compile", "test", "jar")
    plan.forEach { println("executing " + it) }
}

Output:

executing compile
executing test
executing jar

The plan reflects a resolved dependency order: jar depends on test, which depends on compile, so Gradle schedules them compile-first. Running the requested jar task pulls in its prerequisites automatically, which is why you rarely invoke compile directly -- asking for the downstream task runs the whole chain. Declaring dependsOn relationships, rather than ordering tasks by hand, lets Gradle compute a correct schedule even as the graph grows.

compileOnly and runtimeOnly scope by phase

Some dependencies are needed only while compiling and others only at runtime. Modelling which end up on the runtime classpath makes the distinction concrete:

data class Dep(val name: String, val atCompile: Boolean, val atRuntime: Boolean)

fun runtimeClasspath(deps: List<Dep>): List<String> =
    deps.filter { it.atRuntime }.map { it.name }

fun main() {
    val deps = listOf(
        Dep("lib-core", atCompile = true, atRuntime = true),      // implementation
        Dep("annotations", atCompile = true, atRuntime = false),  // compileOnly
        Dep("db-driver", atCompile = false, atRuntime = true)     // runtimeOnly
    )
    println("runtime classpath: " + runtimeClasspath(deps))
}

Output:

runtime classpath: [lib-core, db-driver]

The runtime classpath keeps only dependencies present at runtime. lib-core (an ordinary implementation dependency) is there; db-driver (a runtimeOnly dependency, such as a JDBC driver loaded reflectively) is there too; but annotations (a compileOnly dependency, needed only to compile against and stripped from the artifact) is excluded. Getting this wrong in either direction fails at runtime: a runtime-needed library marked compileOnly throws NoClassDefFoundError, while a compile-only annotation left as implementation needlessly bloats the shipped artifact.


Real World Example: A Leaked Transitive Dependency

A team publishes an auth-lib that uses a JSON library internally to parse tokens. In the build script they declare the JSON library with api instead of implementation -- a small slip. Consumers of auth-lib now see the JSON library on their classpath, and one of them starts using its types directly. Later the auth-lib team swaps to a different JSON library.

data class Dep(val name: String, val api: Boolean)

fun consumerSees(deps: List<Dep>): List<String> =
    deps.filter { it.api }.map { it.name }   // only api deps leak to consumers

fun main() {
    // v1: internal JSON lib mistakenly declared api (should be implementation)
    val v1 = listOf(Dep("auth-public", true), Dep("json-v1", true))
    val visV1 = consumerSees(v1)
    println("consumer sees on v1: " + visV1)
    println("consumer used json-v1, compiles on v1? " + ("json-v1" in visV1))

    // v2: auth-lib swaps its internal JSON implementation
    val v2 = listOf(Dep("auth-public", true), Dep("json-v2", true))
    val visV2 = consumerSees(v2)
    println("consumer used json-v1, compiles on v2? " + ("json-v1" in visV2))
}

Output:

consumer sees on v1: [auth-public, json-v1]
consumer used json-v1, compiles on v1? true
consumer used json-v1, compiles on v2? false

At first everything works. Because the JSON library is declared api, it leaks onto the consumer's classpath alongside the intended auth-public surface, so visV1 contains "json-v1". The consumer references a json-v1 type and compiles fine -- "compiles on v1? true". Nothing warns anyone that the consumer is now coupled to auth-lib's private choice of JSON parser.

Then the auth-lib team does something entirely reasonable: they replace their internal JSON parser, moving from json-v1 to json-v2. From their perspective this is an internal change with no public-API impact. But the consumer that leaned on the leaked json-v1 type no longer finds it on the classpath -- "compiles on v2? false" -- and their build breaks, through no change of their own.

The genuine design flaw is declaring an internal dependency api when it should have been implementation, leaking it transitively to consumers who then couple to it. The convenience of "everything is visible" quietly turns a private implementation detail into part of the public contract, so a routine internal upgrade becomes a breaking change for everyone downstream. The fix is to declare the JSON library implementation, so it never appears on any consumer's classpath; the consumer physically cannot depend on it, and swapping it becomes invisible. The broader limitation is that api widens your module's public surface to include everything it transitively exposes, and every leaked dependency is a future breaking change waiting to happen -- which is why implementation should be the default and api the deliberate exception for types that truly belong to your interface.


Common Mistakes

  1. Using api where implementation suffices. An api dependency leaks onto every consumer's classpath, coupling them to your private choices. Default to implementation and reserve api for types in your public signatures.
  1. Using implementation where api is needed. If a public method returns a type from a dependency, that dependency must be api or consumers cannot name the type. implementation hides it and breaks their compile.
  1. Hard-coding versions across modules. Scattering version numbers lets them drift apart. Centralise them in a version catalog so every module resolves the same coordinates.
  1. Putting test-only dependencies on the main classpath. A test framework declared implementation ships in production. Use testImplementation so it stays out of the runtime artifact.
  1. Ordering tasks manually instead of with dependsOn. Hand-sequencing tasks is fragile as the build grows. Declare dependencies and let Gradle compute the order.
  1. Confusing compileOnly with implementation. compileOnly omits the dependency at runtime; using it for something needed at runtime causes a NoClassDefFoundError in production.
  1. Ignoring the Kotlin DSL's type safety. Writing build.gradle.kts as if it were untyped Groovy misses completion and compile-time checks. Lean on the typed accessors the Kotlin DSL provides.
  1. Duplicating configuration across subprojects. Repeating the same plugin and dependency setup in every module invites drift. Extract shared configuration into convention plugins or the root build.
  1. Depending on transitive dependencies you did not declare. Relying on a library that only arrives transitively means an upstream change can remove it. Declare every dependency you use directly.

Best Practices

  • Default every dependency to implementation, promoting to api only when a type genuinely appears in your module's public API.
  • Keep versions in a single version catalog so all modules share one source of truth for coordinates.
  • Use testImplementation, compileOnly, and runtimeOnly to scope dependencies to exactly when they are needed.
  • Declare task relationships with dependsOn and let Gradle schedule them, rather than ordering tasks by hand.
  • Declare directly every dependency your code uses, never relying on it arriving transitively.
  • Exploit the Kotlin DSL's type safety and IDE completion instead of treating the build script as untyped text.
  • Extract shared build logic into convention plugins to avoid drift across a multi-module project.
  • Follow the standard layout (src/main/kotlin, src/test/kotlin, one module per coherent unit) so the structure is predictable.

Practice Exercises

  1. Model consumer visibility: given a list of dependencies flagged api or not, write a function returning what a consumer sees, and confirm implementation deps are excluded.
  1. Write a version-catalog lookup from alias to version that errors on an unknown alias, and confirm both a known and an unknown lookup behave correctly.
  1. Reproduce the leak flaw: mark an internal dependency api, show a consumer coupling to it, then simulate swapping the internal dependency and show the consumer breaks. Fix it by making the dependency non-api.
  1. Model a task chain with dependsOn relationships and print the resolved execution order, confirming prerequisites run before the task that needs them.