404 Not Found

404 Not Found


nginx

Kotlin Environment Setup and Project Scaffolding

From JDK to Gradle, from kotlinc REPL to IntelliJ IDEA — set up your Kotlin development environment in 5 minutes and get Alice's OrderProcessor project running.

1. What You'll Learn


2. A Newcomer's Real Story

(1) Pain Point: Environment Setup Feels Like a Maze

Alice is a new developer on the team. Day one task: set up the OrderProcessor development environment. She spent 3 hours wrestling with JDK versions, Gradle configuration, and IDE plugins — without running a single Hello World.

(2) Standardized Setup Workflow

BASH
# Step 1: Install JDK 17 (LTS)
# Step 2: Install IntelliJ IDEA
# Step 3: Create Gradle project with Kotlin DSL
# Step 4: Run Hello World in 5 minutes

Following a standardized workflow, Alice completed environment setup and ran her first program in 5 minutes.


3. JDK Installation and Configuration

(1) JDK Version Selection

Version Type Recommendation Notes
JDK 17 LTS ⭐⭐⭐ Long-term support, minimum for Spring Boot 3.x
JDK 21 LTS ⭐⭐⭐ Latest LTS, virtual thread support
JDK 8 Legacy Legacy project maintenance, not for new projects
JDK 11 Old LTS ⭐⭐ Transitional version; new projects should use 17+

(2) Installation and Environment Variables

BASH
# macOS (Homebrew)
brew install openjdk@17

# Ubuntu/Debian
sudo apt install openjdk-17-jdk

# Windows - download from adoptium.net
# Then set environment variables
BASH
# Verify installation
java -version
# openjdk version "17.0.x" ...

# Set JAVA_HOME (add to ~/.bashrc or ~/.zshrc)
export JAVA_HOME=$(/usr/libexec/java_home -v 17)  # macOS
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk     # Linux
100%
flowchart TD
    A[Download JDK 17] --> B[Install JDK]
    B --> C[Set JAVA_HOME]
    C --> D[Add to PATH]
    D --> E{java -version OK?}
    E -->|Yes| F[Proceed to IDE]
    E -->|No| G[Check PATH config]
    G --> C

4. IntelliJ IDEA Installation

(1) Version Selection

Version Price Kotlin Support Best For
IDEA Ultimate Paid Full (Spring/KMP/Compose) Enterprise developers
IDEA Community Free Basic Kotlin support Individual learners
Fleet Preview Next-gen IDE Early adopters

(2) Kotlin Plugin Verification

TEXT
IntelliJ IDEA → Settings → Plugins → Installed
  ✅ Kotlin (bundled since 2020.x)
  ✅ Gradle (bundled)
💡 Tip: IntelliJ IDEA 2020.x and later ship with the Kotlin plugin built in — no manual installation needed.


5. Gradle Kotlin DSL Project Setup

(1) Project Structure

TEXT
order-processor/
├── build.gradle.kts        # Build configuration (Kotlin DSL)
├── settings.gradle.kts     # Project settings
├── gradle/
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── src/
│   ├── main/
│   │   └── kotlin/
│   │       └── com/order/
│   │           └── Main.kt
│   └── test/
│       └── kotlin/
│           └── com/order/
│               └── MainTest.kt
└── gradlew / gradlew.bat   # Gradle wrapper scripts

(2) build.gradle.kts

KOTLIN
// build.gradle.kts
plugins {
    kotlin("jvm") version "1.9.22"
    application
}

group = "com.order"
version = "1.0.0"

repositories {
    mavenCentral()
}

dependencies {
    implementation(kotlin("stdlib"))
    testImplementation(kotlin("test"))
    testImplementation("org.junit.jupiter:junit-jupiter:5.10.1")
}

tasks.test {
    useJUnitPlatform()
}

application {
    mainClass.set("com.order.MainKt")
}

kotlin {
    jvmToolchain(17)
}

(3) settings.gradle.kts

KOTLIN
// settings.gradle.kts
rootProject.name = "order-processor"

6. Your First Kotlin Program

(1) Write Main.kt

KOTLIN
// src/main/kotlin/com/order/Main.kt

fun main() {
    println("Hello, OrderProcessor!")

    val orderCount = 1_500
    val dailyRevenue = 89_500.50

    // String template with expression
    println("Today's stats: $orderCount orders, \$$dailyRevenue USD revenue")
}

(2) Run Methods Comparison

Method Command Use Case
Gradle ./gradlew run Standard for production projects
IDE Click green triangle Daily dev and debugging
kotlinc kotlinc ... CLI packaging
REPL kotlinc interactive Quick experimentation

(3) Expected Output

TEXT
Hello, OrderProcessor!
Today's stats: 1500 orders, $89500.50 USD revenue

7. REPL Interactive Playground

Kotlin includes a built-in REPL (Read-Eval-Print Loop) perfect for quickly testing code snippets.

BASH
$ kotlinc
Welcome to Kotlin version 1.9.22
Type :help for help, :quit for quit
>>> val orderTotal = 299.99
>>> println("Order total: \$$orderTotal USD")
Order total: $299.99 USD
>>> "ORD-${1001}".also { println(it) }
ORD-1001
>>> :quit

(1) REPL Quick Commands

Command Function
:help Show help
:quit Exit REPL
:history View input history
:dump View defined classes

8. Complete Example: Alice's OrderProcessor Bootstrap

KOTLIN
// ============================================
// OrderProcessor - Project Bootstrap
// Feature: Initialize project with basic domain models
// ============================================

// Domain model
data class Order(val id: String, val total: Double, val status: String)

// Business logic
fun calculateTax(order: Order, rate: Double = 0.08): Double {
    return order.total * rate
}

fun formatReceipt(order: Order, tax: Double): String {
    val grandTotal = order.total + tax
    return """
        |========================================
        |  Order Receipt
        |========================================
        |  Order ID  : ${order.id}
        |  Subtotal  : $${order.total} USD
        |  Tax (8%)  : $$tax USD
        |  Grand Total: $$grandTotal USD
        |  Status    : ${order.status}
        |========================================
    """.trimMargin()
}

fun main() {
    val order = Order("ORD-001", 299.99, "CONFIRMED")
    val tax = calculateTax(order)
    val receipt = formatReceipt(order, tax)
    println(receipt)

    // Process multiple orders
    val orders = listOf(
        Order("ORD-002", 1_500.00, "PROCESSING"),
        Order("ORD-003", 45.50, "SHIPPED"),
        Order("ORD-004", 8_900.00, "CONFIRMED")
    )

    val totalRevenue = orders.sumOf { it.total }
    println("\nTotal revenue: \$$totalRevenue USD across ${orders.size} orders")
}

Output:

TEXT
========================================
  Order Receipt
========================================
  Order ID  : ORD-001
  Subtotal  : $299.99 USD
  Tax (8%)  : $23.999200000000002 USD
  Grand Total: $323.9892 USD
  Status    : CONFIRMED
========================================

Total revenue: $10445.5 USD across 3 orders

❓ FAQ

Q Must I use Gradle with Kotlin? Can I use Maven?
A You can use Maven, but Gradle Kotlin DSL is the official recommendation. The Kotlin DSL build configuration is itself type-safe Kotlin code.
Q Can Kotlin run on JDK 8?
A Yes. Kotlin supports JDK 8+, but new projects should use JDK 17 LTS for better performance and feature support.
Q Is IntelliJ IDEA Community enough?
A For pure Kotlin/JVM learning, yes. But Spring Boot development and KMP multiplatform require the Ultimate edition.
Q What if the kotlinc command is not found?
A The Kotlin compiler ships with IntelliJ IDEA, or you can install it separately via sdkman or brew.
Q What's the difference between Gradle Kotlin DSL and Groovy DSL?
A Kotlin DSL uses Kotlin for build scripts, offering type hints and compile-time checking. Groovy DSL is more flexible but lacks type safety. Kotlin DSL is recommended for new projects.
Q What if I get "Main class not found" at runtime?
A Check that mainClass in build.gradle.kts points to the correct class name (note the Kt suffix: MainMainKt).

▶ Example: Install via sdkman

BASH
curl -s "https://get.sdkman.io" | bash
sdk install kotlin
kotlinc -version

Output:

TEXT
kotlinc-jvm 2.0.21 (JRE 17.0.11)

▶ Example: Create a Gradle Project

BASH
gradle init --type kotlin-application --dsl kotlin
./gradlew run

Output:

TEXT
BUILD SUCCESSFUL

▶ Example: REPL Interactive

KOTLIN
>>> val x = 10
>>> val y = 20
>>> x + y
30

Output:

TEXT
30

📖 Summary


📝 Exercises

  1. Beginner (⭐) : Install JDK 17 + IntelliJ IDEA, create a Gradle Kotlin DSL project, and run Hello World. Hint: see Section 6
  2. Intermediate (⭐⭐) : Modify build.gradle.kts to add the kotlinx.coroutines dependency. Hint: implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
  3. Challenge (⭐⭐⭐) : Write a script with kotlinc that reads command-line arguments and prints an order summary. Hint: args gives CLI arguments, kotlinc -script runs

← Previous | Next →

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏