KtKotlin
AdvancedLesson 16 of 16

Gradle, Tests, Java Interop & Multiplatform – Kotlin

Setting up a project, testing, and mixing Kotlin with Java and other platforms.

You usually build Kotlin projects with Gradle and the Kotlin DSL. The file build.gradle.kts is itself Kotlin code (with autocompletion). For the versions, use the current Kotlin and coroutines versions.

plugins {
    kotlin("jvm") version "2.1.0"
    application
}

repositories { mavenCentral() }

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
    testImplementation(kotlin("test"))
}

kotlin { jvmToolchain(21) }
application { mainClass.set("MainKt") }    // Main.kt with fun main()
tasks.test { useJUnitPlatform() }
./gradlew run       # start the program
./gradlew test      # run the tests
./gradlew build     # build everything

You write tests with kotlin.test (which runs on JUnit 5). In Kotlin, test names may even be written in backticks, but simple function names are enough:

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith

fun teile(a: Int, b: Int) = a / b

class RechnerTest {
    @Test
    fun teiltZahlen() = assertEquals(3, teile(9, 3))

    @Test
    fun teilenDurchNullWirftFehler() {
        assertFailsWith<ArithmeticException> { teile(1, 0) }
    }
}

Kotlin and Java can be mixed in the same project. For nice Java calls, annotations such as @JvmStatic, @JvmOverloads (generates overloads for default values), and @Throws help:

class Util {
    companion object {
        @JvmStatic
        fun hallo(name: String = "World") = "Hello $name"
    }
}

@JvmOverloads
fun gruss(name: String, gruss: String = "Hello") = "$gruss, $name!"
  • Kotlin/JVM: backend (Spring Boot, Ktor), Android, desktop (Compose)
  • Kotlin/JS: compilation to JavaScript for the web
  • Kotlin/Native: machine code without a JVM (iOS, Linux, Windows, macOS)
  • Kotlin Multiplatform (KMP): shared logic (networking, data models) for Android, iOS, web, and server
  • Compose Multiplatform: shared user interfaces
TipSpring Boot, Ktor, Exposed, and Jetpack Compose are the most common frameworks in the Kotlin ecosystem. To get started with Android, use the Android Studio template "Empty Activity" with Compose.