Skip to content
Tutorials Center
My learning

Topics

Lesson 109 of 134 ยท Testing and Tooling

Project Structure and Modules

Learn how a real Kotlin project is organized: source sets, packages, files, modules, visibility across them, layering and dependency direction, and how libraries are published.

Everything so far fit into one file. Real projects do not: a typical application has hundreds of files, several teams, a build tool and often more than one deliverable (a server, a command-line client, a shared library). The question "where does this code go?" decides how easy the project is to read, test and change two years from now.

This lesson shows the vocabulary and the conventions: source sets, packages, files, modules and layers, and how Kotlin's visibility rules tie them together. The runner on this site compiles exactly one file and has no build tool, so the layout parts are shown as read-only snippets, and we use runnable single-file stand-ins to experiment with the ideas that do not need a build: visibility boundaries, dependency direction and wiring. It builds on Packages and Imports, Visibility Modifiers and Gradle Basics for Kotlin.

The standard layout

Almost every Kotlin project built with Gradle uses the same folder layout, inherited from the Java world. This is read-only: it is a directory tree, not a program.

TEXT
shop/                          <- project root
โ”œโ”€โ”€ settings.gradle.kts        <- names the project, lists the modules
โ”œโ”€โ”€ build.gradle.kts           <- build script
โ”œโ”€โ”€ gradle/libs.versions.toml  <- version catalog (one place for versions)
โ””โ”€โ”€ src/
    โ”œโ”€โ”€ main/
    โ”‚   โ”œโ”€โ”€ kotlin/            <- production code
    โ”‚   โ”‚   โ””โ”€โ”€ com/example/shop/
    โ”‚   โ”‚       โ”œโ”€โ”€ Main.kt
    โ”‚   โ”‚       โ”œโ”€โ”€ domain/Order.kt
    โ”‚   โ”‚       โ””โ”€โ”€ data/OrderRepository.kt
    โ”‚   โ””โ”€โ”€ resources/         <- config files, templates, static data
    โ””โ”€โ”€ test/
        โ”œโ”€โ”€ kotlin/            <- test code (same packages, different folder)
        โ”‚   โ””โ”€โ”€ com/example/shop/domain/OrderTest.kt
        โ””โ”€โ”€ resources/

src/main and src/test are source sets: groups of files compiled together with their own dependencies. Tests can see production code, but production code can never see tests. That one-way arrow is the reason test helpers and fake classes live under src/test and never ship to users.

Kotlin does not force the folders to match the packages, but everyone does it anyway. A file src/main/kotlin/com/example/shop/domain/Order.kt starts with package com.example.shop.domain. IDEs warn when the two disagree, and tools such as coverage reports and Java interop expect the match.

The reversed domain name (com.example) is a convention to make packages unique across the world: if you publish a library, nobody else should own com.example.shop. For an application nobody else will import, a short prefix is fine, but a consistent one is still worth having.

Files are not classes

Unlike Java, a Kotlin file may hold many top-level declarations: several classes, functions, constants and extension functions. A good rule of thumb is that a file groups things that change together. A small sealed interface with its three or four implementations belongs in one file. A large class gets a file of its own. Utility functions that extend one type go in a file named after it, for example StringExtensions.kt.

On the JVM, top-level functions and properties must live in a class, so the compiler generates one named after the file: Order.kt becomes the class OrderKt. That is what Java code sees, and you can change it with @file:JvmName. In this runner the file is called main.kt, so the generated class is MainKt. You can look at it from running code:

Kotlin Top-level code lives in a generated class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

object {}.javaClass.enclosingClass asks the anonymous object which class it was declared in, which is the file's facade class MainKt. shout is a static method on it, just like main. You never write that class yourself; you only need to know it exists when Java calls your code (see Java Interoperability).

Packages group, modules separate

A package is a namespace inside one compiled unit. A module is a compiled unit: a set of source files built together into one artifact (a JAR on the JVM) with an explicit list of dependencies. In Gradle every subproject is a module.

Why split a project into several modules, when packages already organize the code?

  • Enforced boundaries. Code in module domain cannot use anything from module server unless domain declares that dependency. A package rule is a convention; a module rule is checked by the compiler.
  • Faster builds. Gradle only recompiles modules whose inputs changed and can build independent modules in parallel.
  • Reuse. The domain module can be used by the server, a command-line tool and an Android app without dragging in a web framework.
  • Smaller deliverables. Each application includes only the modules it needs.

A multi-module project, again read-only:

Kotlin
// read-only example: settings.gradle.kts of a three-module project
rootProject.name = "shop"

include(":domain")   // pure business rules, no framework
include(":data")     // database access, depends on :domain
include(":server")   // web layer and main(), depends on both
Kotlin
// read-only example: server/build.gradle.kts
plugins {
    kotlin("jvm")
    application
}

dependencies {
    implementation(project(":domain"))
    implementation(project(":data"))
    testImplementation(kotlin("test"))
}

application {
    mainClass.set("com.example.shop.server.MainKt")
}

implementation(project(":domain")) is how :server declares its dependency. A good dependency graph is a directed acyclic graph with the stable, abstract modules at the bottom and the volatile, framework-heavy ones at the top. Gradle refuses circular module dependencies, which is a feature: a cycle usually means two things should be one module, or a third thing is missing.

Do not start with ten modules. A single module with clean packages is simpler and can be split later; splitting becomes worthwhile when a boundary matters (a second app wants to reuse the code, or build times hurt).

internal: visibility at the module boundary

Kotlin has a visibility level that Java does not: internal means "visible everywhere inside the same module, hidden from other modules". It is the tool for a library's implementation details: public types form the API, and internal helpers can change at will, because no outside module can reference them.

On this site everything is one module, so we cannot demonstrate a module boundary directly. But we can see the other visibility levels working, with the real error messages. First, private at the top level means "private to this file":

Kotlin Calling a private member (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler stops with main.kt:12:21: error: cannot access 'var balance: Int': it is private in 'Account'. The fix is to expose what callers need, not the field itself: a read-only property such as val balance: Int get() = ... or a method.

Kotlin The API is small, the internals are hidden

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Callers only know Counter and counter(...). The class CounterImpl could be renamed, split in two or replaced by a faster version without breaking anybody. This pattern, a small interface plus a factory function, shows up everywhere in well-designed libraries. For why this matters see Encapsulation and Design.

Make the default internal or private and promote to public deliberately. Everything public is a promise to every user of your library. Kotlin's explicit API mode (kotlin { explicitApi() } in Gradle) forces every public declaration to state its visibility and return type, which helps library authors avoid accidental promises.

Layers and the direction of dependencies

Packages and modules answer "where does it live?". The next question is "who may depend on whom?". The most common answer is layers:

  • domain: your business concepts and rules (Order, Money, "an order cannot ship twice"). Pure Kotlin, no frameworks.
  • data (or infrastructure): databases, files, network clients. Implements interfaces declared by the domain.
  • application / server: wires everything together and talks to the outside world (HTTP, command line, a UI).

The rule that keeps this healthy: dependencies point inward. The domain knows nothing about the database; the database code depends on the domain. When the domain needs storage, it declares an interface for what it needs (OrderRepository), and the data layer provides an implementation. The main function, called the composition root, is the only place that knows all the concrete classes and connects them.

Here is the whole structure in one file, with comments marking which part would live in which module:

Kotlin Three layers in one file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Look at what OrderService does not contain: any mention of InMemoryOrderRepository. Because of that, a test can pass a different repository, and replacing the in-memory store with a SQL database means writing one new class and changing one line of main. This technique is called dependency injection; frameworks automate it, but passing arguments to constructors by hand, as above, is dependency injection too, and for small and medium projects it is often all you need. Test Doubles builds on this structure.

What goes wrong without structure

Three symptoms tell you the structure is failing:

  1. A cycle between packages: domain imports something from server "just this once". Fix by moving the shared type down, or by introducing an interface.
  2. A utils or common package that grows forever. It becomes a dumping ground that everything depends on. Name packages after what they do (pricing, shipping), not what they are.
  3. Framework types in business code: an HTTP request object or a database annotation inside Order. Keep the domain framework-free and convert at the boundary.

Organizing by feature or by layer

You can slice a project in two ways. By layer gives you packages controllers, services, repositories; every feature touches all three folders. By feature gives you orders, customers, billing, each containing its own service, repository and model. Feature packages keep related code together, let you make most things internal or private to the feature and make it easy to delete or extract a feature. Most teams that start by layer move to feature packages as the project grows, optionally with layers inside each feature. Pick one rule and apply it everywhere; consistency matters more than which you choose.

Libraries and publishing

A library is a module published for others. In the JVM world the target is a Maven repository (Maven Central or a private one), where an artifact is identified by three coordinates: group (com.example), name (shop-domain) and version (1.4.0). Publishing is configured in Gradle (read-only):

Kotlin
// read-only example: build.gradle.kts of a library module
plugins {
    kotlin("jvm")
    `maven-publish`
}

group = "com.example"
version = "1.4.0"

kotlin {
    explicitApi()          // every public declaration must be spelled out
}

publishing {
    publications {
        create<MavenPublication>("library") {
            from(components["java"])
            artifactId = "shop-domain"
        }
    }
}

Library authors follow semantic versioning: MAJOR.MINOR.PATCH. Fix a bug and bump the patch; add a feature compatibly and bump the minor; break callers and bump the major. Because anything public is part of the contract, the discipline from the internal section above is what lets you keep that promise. Kotlin also has tools to check it: the binary compatibility validator plugin records your public API in a file and fails the build when a change would break existing users.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which source set can see the other?

    Tests depend on the production code they check. Production code never depends on tests, so test helpers are not shipped.
  2. 2. What does internal mean in Kotlin?

    internal is module-wide: other modules cannot reference the declaration, which makes it ideal for implementation details of a library.
  3. 3. A top-level function shout is declared in Order.kt on the JVM. Which class does the compiler put it in?

    The compiler creates a facade class named after the file plus Kt. In this runner the file is main.kt, so it is MainKt.
  4. 4. In a layered design, where should the interface OrderRepository normally be declared?

    Dependencies point inward: the domain declares what it needs and the data layer implements it, so the domain never imports database code.
  5. 5. Why is a growing utils package a warning sign?

    Packages named after what they are rather than what they do collect unrelated code. Name packages after features or responsibilities.

Summary

  • Gradle projects use src/main/kotlin and src/test/kotlin as source sets; tests see production code, never the reverse.
  • Packages follow the folder structure by convention; one file may hold many related top-level declarations and compiles to a FileNameKt class on the JVM.
  • A module is a separately compiled unit with declared dependencies; split into modules when a boundary needs enforcing, not by default.
  • internal hides declarations from other modules; keep the public API small and prefer private and internal first.
  • Let dependencies point inward: the domain declares interfaces, the data layer implements them and main wires everything together.
  • Organize by feature as projects grow, avoid utils dumping grounds, and publish libraries with explicit APIs and semantic versions.

Next: Java Interoperability