The user is initializing a new Kotlin project and needs to choose between Gradle (Kotlin DSL), Maven, or other build tooling with proper Kotlin compiler plugin configuration
The user wants to set up a production-ready Kotlin project with proper multimodule structure, code quality gates, coroutines support, and serialization
Guides expert-level kotlin project setup implementation: kotlin and best-practices decision frameworks, production-ready patterns, and concrete templates for kotlin project setup workflows.
How much does it cost?+
Nothing. It ships with Murage, which is open source. Your bots run on the AI plan you already have.
Can I change it?+
Yes. Open it in Settings → Skills to read, edit or duplicate it. Skill Guard scans it again after every edit.
Give your first job to Murage.
Download the app, connect the AI you already pay for, and tell your Chief of Staff what needs doing. Plan on about ten minutes from install to a working team.
The user is migrating a Java project to Kotlin and needs guidance on coexistence configuration, @JvmStatic, @JvmOverloads, and incremental migration strategy
The user needs to configure Kotlin for a specific runtime target -- JVM backend (Spring Boot, Ktor, Quarkus), Android, Kotlin/JS, or Kotlin Multiplatform Mobile (KMM)
The user wants to establish team-wide conventions including opt-in API configuration, explicit API mode, compiler flags, and lint rules using detekt or ktlint
The user is setting up CI/CD pipelines that compile Kotlin correctly with incremental compilation, build caching, and parallel execution
The user wants to configure the Kotlin compiler for strict null safety, progressive mode, or specific JVM target bytecode version
Do NOT use this skill when:
The user needs help with Kotlin syntax, language features, or algorithms -- those are language learning questions, not project setup
The user is configuring Android-specific concerns like Gradle AGP versioning, ProGuard/R8 rules, or Android SDK targets -- check the android-project-setup skill
The user needs Kotlin Multiplatform project scaffolding with shared modules for iOS/Android -- check the kotlin-multiplatform skill if available
The user is asking about deploying a Kotlin application (Docker, Kubernetes, cloud) -- check the deployment skills in the infrastructure subcategory
The user needs help with specific Kotlin frameworks like Spring Boot or Ktor in depth -- check framework-specific skills
The user wants general JVM tuning (heap sizing, GC selection, JFR) -- check the jvm-performance skill
Process
1. Determine the Kotlin Target Platform and Runtime
Before writing a single line of configuration, establish the deployment target because it determines the entire dependency graph, compiler options, and plugin set.
JVM backend: Standard Kotlin JVM target. Confirm the JDK version (LTS: 17 or 21 preferred in 2024+). Set jvmTarget in compileKotlin to match -- mismatches between the JDK version and jvmTarget cause subtle bytecode issues.
Kotlin/JVM with framework: Identify Spring Boot (Spring plugin + kotlin-spring plugin required for open classes), Ktor (no special compiler plugins but needs coroutines), or Quarkus (Quarkus Kotlin extension + all-open plugin for CDI).
Kotlin Multiplatform: Identify shared vs. platform-specific source sets (commonMain, jvmMain, iosMain). This requires kotlin-multiplatform plugin and cannot coexist simply with kotlin("jvm").
Kotlin/JS or Kotlin/Wasm: Confirm browser vs. Node.js target and IR backend requirement (legacy backend is deprecated as of Kotlin 1.9).
Confirm the Kotlin version to use. As of 2024, Kotlin 2.0.x is stable with K2 compiler. Kotlin 1.9.x is the LTS-stable fallback. K2 brings 2x faster compilation but has different plugin compatibility requirements.
2. Choose and Configure the Build System
The build system is the backbone of the project. Kotlin DSL for Gradle is the strongly preferred choice for new Kotlin projects.
Gradle with Kotlin DSL (build.gradle.kts): Use this for all new JVM/KMP projects. It provides IDE completion, type safety, and is the canonical Kotlin tooling path. Use Gradle 8.5+ for Kotlin 2.x support.
Maven: Use only if your organization mandates Maven or you are integrating into an existing Maven monorepo. Maven Kotlin compilation is slower and has less community momentum. Use kotlin-maven-plugin version matching the Kotlin version exactly.
Convention plugins (Gradle): For multimodule projects, extract shared build logic into buildSrc or gradle/libs.versions.toml + precompiled script plugins in an included build. Never duplicate build.gradle.kts logic across modules.
Configure gradle/libs.versions.toml (Gradle version catalog) for all dependency versions. This is mandatory for teams of 3+ to prevent version drift:
3. Configure the Kotlin Compiler Plugin and Core Options
Compiler configuration is where most teams make critical mistakes. Get this right at day one.
In build.gradle.kts, configure compileKotlin and compileTestKotlin tasks:
kotlin
tasks.withType<KotlinCompile>().configureEach {
compilerOptions {
jvmTarget.set(JvmTarget.JVM_21)
freeCompilerArgs.addAll(
"-Xjsr305=strict", // Treat Spring/JSR-305 nullability annotations as strict
"-Xemit-jvm-type-annotations", // Preserve type annotations in bytecode
"-opt-in=kotlin.RequiresOptIn" // Enable opt-in API mechanism globally
)
allWarningsAsErrors.set(true) // In new projects -- enforce from day one
progressiveMode.set(true) // Get deprecation warnings for upcoming Kotlin changes
}
}
-Xjsr305=strict: Critical for Spring Boot interop. Without it, Spring's @Nullable and @NonNull annotations are ignored by the Kotlin compiler, defeating null safety.
Explicit API mode: For library projects or shared modules, add explicitApi() to the kotlin {} block. This forces visibility modifiers on all public declarations and prevents accidental API surface exposure.
jvmTarget alignment: If using JDK 21 but setting jvmTarget = JVM_17, ensure the Gradle java plugin also targets 17 via java { sourceCompatibility = JavaVersion.VERSION_17 }. Mismatch causes IncompatibleClassChangeError at runtime.
K2 compiler (Kotlin 2.0+): The K2 compiler is default. Ensure all annotation processors (kapt) or KSP processors are K2-compatible. Prefer KSP over kapt for new projects -- kapt requires a separate Kotlin compilation round and is significantly slower.
4. Set Up Essential Kotlin Dependencies
Define a canonical dependency baseline for the project type.
All JVM projects:
kotlin
dependencies {
implementation(kotlin("stdlib"))
// Do NOT add kotlin-stdlib-jdk8 or kotlin-stdlib-jdk7 separately for Kotlin 1.8+
// they are merged into kotlin-stdlib
}
Coroutines (any project doing async I/O or concurrent work):
kotlin
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.1")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.8.1") // For JDK8 integration
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.8.1")
Serialization: For JSON/Protobuf without reflection overhead. Add the plugin in plugins {} block AND the runtime dependency:
kotlin
// plugins block
kotlin("plugin.serialization") version libs.versions.kotlin.get()
// dependencies block
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
Testing baseline: Use JUnit 5 (Jupiter) with Kotest assertions or MockK for idiomatic Kotlin testing:
Run ./gradlew ktlintFormat as a pre-commit hook. Run ./gradlew ktlintCheck in CI (fail the build on violations).
detekt (static analysis): Add io.gitlab.arturbosch.detekt plugin. Generate a baseline config: ./gradlew detektGenerateConfig. The default detekt.yml is a starting point -- tune it per team. Enable type resolution for stronger checks:
kotlin
detekt {
config.setFrom("$projectDir/config/detekt/detekt.yml")
buildUponDefaultConfig = true
allRules = false // Only enable rules you enforce
}
Key detekt rules to enable from day one: MagicNumber, ComplexCondition, LongParameterList (threshold: 6), TooManyFunctions (threshold: 11 per class), MaxLineLength.
Binary compatibility validator: For library/shared module projects, add org.jetbrains.kotlinx.binary-compatibility-validator. This generates a .api file tracking public API surface and fails CI when the API changes unexpectedly.
Configure all quality checks to run in the check Gradle lifecycle task so ./gradlew check is the single CI quality gate command.
6. Establish Project Structure and Module Boundaries
Project structure communicates architectural intent and prevents coupling.
Single-module small projects (1-5 engineers, bounded domain):
Multimodule projects (5+ engineers, multiple bounded contexts): Use Gradle multi-project builds with a settings.gradle.kts including all subprojects. Place shared build logic in build-logic/ as an included Gradle build with convention plugins (e.g., kotlin-library-conventions.gradle.kts, kotlin-service-conventions.gradle.kts).
Define integration test source sets explicitly -- do not put integration tests in src/test. Create a dedicated integrationTest source set that runs against a real database or external service, separated from unit tests in CI:
Enforce module boundaries using detekt's ForbiddenImport or ArchUnit tests. Domain modules must not import infrastructure modules.
7. Configure CI/CD Integration
Kotlin's compilation speed and incremental compilation behavior require specific CI configuration.
Gradle remote build cache: Configure Gradle Enterprise or Develocity for build cache sharing across CI agents. Without this, Kotlin compilation time on CI is 3-5x local times for large projects.
Parallel compilation: In gradle.properties:
properties
org.gradle.parallel=true
org.gradle.workers.max=4 # Set to CPU count - 1 on CI agents
kotlin.incremental=true
kotlin.incremental.multiplatform=true
kotlin.daemon.jvm.options=-Xmx2g # Kotlin daemon heap -- 2GB for medium projects, 4GB for large
org.gradle.jvmargs=-Xmx4g -XX:+UseParallelGC
GitHub Actions / GitLab CI caching: Cache both the Gradle user home (~/.gradle/caches) and the project .gradle directory. Cache key must include the hash of all *.gradle.kts files and libs.versions.toml.
Kotlin daemon on CI: Set GRADLE_OPTS=-Dkotlin.compiler.execution.strategy=in-process on CI to avoid daemon startup overhead in ephemeral build containers.
./gradlew check -- all remaining checks including binary compatibility
8. Document Conventions and Finalize
Set the team up for long-term consistency.
Create a CONTRIBUTING.md documenting: Kotlin version, JDK version, required Gradle wrapper version, how to run quality checks locally, branch naming, and commit message conventions.
Create an ADR/ directory with the first Architecture Decision Record: why Kotlin was chosen, what version, and any deviations from defaults (e.g., "We disabled allWarningsAsErrors in test source sets because MockK generates some deprecation warnings we cannot control").
Add a .kotlin-version file in the project root for tooling that reads it (some IDE plugins use it).
Pin the JDK version using a .java-version or .tool-versions (asdf) file so all developers and CI use the same JDK.
Output Format
When helping a user set up a Kotlin project, provide output in this structure:
## Kotlin Project Setup Plan
### Target Context
- Platform: [JVM / KMP / JS / Wasm]
- Runtime/Framework: [Spring Boot 3.x / Ktor / Quarkus / None]
- Kotlin Version: [2.0.x / 1.9.x]
- JDK Version: [21 / 17 / 11]
- Build System: [Gradle Kotlin DSL / Maven]
- Team Size: [number]
- Module Structure: [Single-module / Multi-module]
### Decision Matrix
| Concern | Choice | Rationale |
|---------------------------|-------------------------------|------------------------------------------------|
| Build system | Gradle 8.x with Kotlin DSL | Type-safe, IDE completion, KMP-ready |
| Dependency management | Version catalog (libs.versions.toml) | Single source of truth for all versions |
| Formatting | ktlint (official style) | Zero-config, integrates with pre-commit |
| Static analysis | detekt with type resolution | Catches architecture and complexity violations |
| Async | kotlinx.coroutines | Structured concurrency, cancellation support |
| Serialization | kotlinx.serialization | Reflection-free, KMP-compatible |
| Testing | JUnit 5 + MockK + Kotest | Idiomatic Kotlin, coroutines test support |
| Java interop | -Xjsr305=strict | Enforces nullability from Java annotations |
### File Listing
[List every file to be created with its purpose]
### settings.gradle.kts
[Complete file content]
### build.gradle.kts (root or module)
[Complete file content]
### gradle/libs.versions.toml
[Complete file content]
### gradle.properties
[Complete file content]
### config/detekt/detekt.yml (key sections)
[Relevant configuration sections]
### .editorconfig
[Complete file content]
### src/main/kotlin/[package]/Application.kt
[Minimal entry point appropriate to the framework]
### CI Configuration (.github/workflows/ci.yml or equivalent)
[Complete CI workflow file]
### Next Steps
1. [Concrete action with command]
2. [Concrete action with command]
3. [Concrete action with command]
Rules
NEVER mix kotlin-stdlib-jdk7 or kotlin-stdlib-jdk8 as explicit dependencies for Kotlin 1.8+. These artifacts were merged into kotlin-stdlib in Kotlin 1.8. Adding them explicitly causes duplicate class warnings and can cause subtle class loading issues at runtime.
ALWAYS align jvmTarget in KotlinCompile tasks with the sourceCompatibility and targetCompatibility in the java plugin. If they differ by even one version, Gradle may compile Java sources to a higher bytecode version than Kotlin sources, causing UnsupportedClassVersionError in production.
NEVER use kapt for new projects that can use KSP. kapt runs a separate compilation round, doubling compile time for annotation-heavy projects. Dagger, Room, Moshi, and most modern processors have KSP support. The annotation processor support for kapt is being formally deprecated.
ALWAYS pin the Kotlin Gradle Plugin version identical to the kotlin-stdlib version. Mismatching plugin and stdlib versions is a top-3 cause of cryptic NoClassDefFoundError and AbstractMethodError at compile time.
NEVER enable allWarningsAsErrors = true on test source sets without accounting for third-party generated code. MockK and similar libraries generate code with deprecation warnings in recent Kotlin versions. Apply the compiler options selectively: tasks.withType<KotlinCompile>().matching { it.name.startsWith("compileMain") }.
ALWAYS use configureEach instead of withType<Task>.configure {} for Kotlin compile task configuration in Gradle.configureEach is lazy and avoids realizing tasks eagerly, which degrades configuration time for large multimodule builds (100+ modules can see 30-60 second overhead from eager task realization).
NEVER commit gradle-wrapper.jar to .gitignore. The wrapper JAR is intentionally committed to the repository. Its SHA is verified by Gradle's built-in wrapper validation. Excluding it forces every developer to run gradle wrapper before building.
ALWAYS configure the Kotlin daemon heap separately from the Gradle daemon heap.org.gradle.jvmargs controls the Gradle daemon. kotlin.daemon.jvm.options controls the Kotlin compiler daemon. For projects with more than 100K lines of Kotlin, the Kotlin daemon needs at least 2GB (-Xmx2g) to avoid GC-induced compilation slowdowns.
NEVER use wildcard imports in Kotlin source files in a team setting. Configure ktlint's no-wildcard-imports rule and detekt's NoWildcardImports rule together. Wildcard imports cause merge conflicts when multiple engineers add imports in the same file and make it impossible to grep for specific class usage.
ALWAYS create a dedicated integrationTest Gradle source set rather than placing integration tests in src/test. Integration tests that start Docker containers (via Testcontainers), make real HTTP calls, or write to real databases must not run with unit tests. Mixing them causes flakey unit test suites and makes fast local feedback loops impossible.
Edge Cases
Kotlin 2.0 K2 Compiler Plugin Incompatibility
If any annotation processor or compiler plugin in the dependency list does not support K2 (check the plugin's changelog for "K2 support" or "Kotlin 2.0 compatible"), the build will fail with This version of the kotlin-plugin requires the K2 compiler or produce incorrect output silently. Handling: Add kotlin.experimental.tryK2=true to gradle.properties first and run ./gradlew build --info to check plugin compatibility before fully committing to Kotlin 2.0. If a plugin is incompatible, either: (a) find the K2-compatible version, (b) temporarily disable that specific plugin's compilation integration, or (c) stay on Kotlin 1.9.x until the plugin is updated. For kapt specifically, K2 kapt is available as kotlin.kapt.use.k2=true but is still experimental -- prefer migrating to KSP instead.
Java/Kotlin Mixed Source Project Migration
When converting an existing Java project to Kotlin incrementally, the java and kotlin source directories must coexist. Handling: Add kotlin("jvm") plugin alongside any existing java plugin. Configure sourceSets.main.kotlin.srcDirs to include both src/main/kotlin and src/main/java if you want Kotlin to process Java sources for type resolution. Use @JvmStatic on companion object methods called from Java, @JvmOverloads for Kotlin default parameter functions called from Java, and @JvmField for constants. Critical: Kotlin sees Java nullability through @Nullable/@NonNull annotations (hence the importance of -Xjsr305=strict). Platform types (types from Java without annotations) are T! in Kotlin -- treat every platform type as potentially null until the Java code is annotated.
Gradle Configuration Cache Incompatibility with Specific Plugins
Configuration cache (org.gradle.configuration-cache=true) breaks plugins that use Project instance at execution time, access task outputs during configuration, or use deprecated APIs. When enabling it, run ./gradlew --configuration-cache build and check for configuration cache problems in the output. Handling: Common offenders are older versions of the Docker plugin, some code generation plugins, and custom buildSrc code that holds task references. Fix by: upgrading the plugin to a CC-compatible version, using @Internal task property annotations correctly, or adding the plugin to a configuration cache exclusion list as a temporary measure. Do not disable configuration cache globally for one non-compliant plugin -- isolate the non-compliant task and run it separately.
Multimodule Build with Shared Kotlin Version
In a multimodule project where some modules are libraries used by other modules, the Kotlin stdlib version must be consistent across all modules. Handling: Define the Kotlin version exclusively in the root libs.versions.toml and apply the Kotlin plugin via a convention plugin in build-logic. Never hardcode the Kotlin version string in a module's build.gradle.kts. Use kotlin("stdlib") without a version when the BOM or version catalog manages the version. Apply platform(kotlin("bom")) in projects where the Kotlin version must be enforced transitively:
Coroutines and suspend Functions in Spring Boot or JPA Context
When using coroutines with Spring Boot, Spring's transaction management and security context propagation do not work with suspend functions by default. Handling: Use kotlinx-coroutines-reactor for Spring WebFlux integration. For Spring MVC (blocking), use runBlocking {} only at the outermost controller layer, never inside service or repository layers. For Spring Security context in coroutines, use SecurityContext with ReactorContextWebFilter. For Spring Data JPA with coroutines, repositories must use @Transactional with a coroutine-aware transaction manager -- do not call suspend JPA operations from a coroutine that doesn't have a Dispatchers.IO context, as JPA blocks threads.
Deterministic Snapshot/Version Handling in CI
Kotlin snapshot versions (2.1.0-SNAPSHOT) are sometimes referenced in tutorials and documentation. Handling: Never use snapshot versions in production projects. Snapshots are published to the Kotlin bootstrap Maven repository, not Maven Central, and can change without notice, causing irreproducible builds. If you need a pre-release, use the RC or beta releases from Maven Central (e.g., 2.1.0-RC). If a team member's ~/.gradle/caches has a snapshot cached, it may differ from a fresh CI environment, causing "works on my machine" failures. Enforce --refresh-dependencies in CI for any snapshot dependency if one accidentally slips through.
OptIn and Experimental API Management
Kotlin's experimental/opt-in API system (formerly @Experimental) is commonly misunderstood. Using any kotlinx.coroutines experimental API, Flow operators marked @FlowPreview, or custom @RequiresOptIn annotations without proper opt-in causes compile errors. Handling: Use @OptIn(ExperimentalCoroutinesApi::class) at the call site for specific functions. For project-wide opt-in (e.g., you're using many coroutines experimental APIs), add to compiler args: -opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi. For your own library code, mark experimental APIs with @RequiresOptIn(level = RequiresOptIn.Level.ERROR) to force callers to explicitly acknowledge the instability. Never add a blanket -opt-in=kotlin.RequiresOptIn that suppresses all opt-in requirements without per-API review.
Windows Build Environment
Kotlin/Gradle builds on Windows have known friction points. Handling: Use WSL2 for development whenever possible -- Gradle's file system watching and incremental compilation work significantly better on Linux (EXT4) than Windows NTFS. If native Windows is required: set GRADLE_USER_HOME to a short path (e.g., C:\gradle) to avoid Windows MAX_PATH (260 characters) issues with deeply nested Gradle cache directories. Enable long path support via Group Policy or git config core.longpaths true. Configure antivirus exclusions for the Gradle cache and build directories -- real-time AV scanning of .class files during compilation is a major performance killer (can increase build times by 40-100%).
Example
Input: "I need to set up a new Kotlin project for a REST API service using Ktor. It's a team of 4 engineers. We're targeting JDK 21, want production-ready quality gates, and will deploy to Kubernetes. This is a greenfield project."
Output:
Kotlin Project Setup Plan
Target Context
Platform: JVM
Runtime/Framework: Ktor 2.3.x (coroutines-native, no Spring)
package com.example.api
import com.example.api.plugins.configureRouting
import com.example.api.plugins.configureSerialization
import com.example.api.plugins.configureStatusPages
import io.ktor.server.application.Application
import io.ktor.server.netty.EngineMain
fun main(args: Array<String>): Unit = EngineMain.main(args)
// Public for testApplication {} to use
fun Application.module() {
configureSerialization()
configureStatusPages()
configureRouting()
}
./gradlew detektGenerateConfig
# Then review and tune config/detekt/detekt.yml
Install the pre-commit hook for ktlint:
bash
./gradlew addKtlintCheckGitPreCommitHook
Verify the full quality gate passes before the first feature commit:
bash
./gradlew check
Create the first ADR in docs/adr/0001-kotlin-ktor-project-setup.md documenting why Ktor was chosen over Spring Boot, the Kotlin version decision, and any non-default compiler flags with their rationale.
Configure branch protection on main to require all CI checks passing before merge, and set the CI workflow as a required status check.