iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Get Started

Install Kotlin via IntelliJ or a CLI, build your first JVM app, run it, write a test.

Kotlin — getting started

EXAMPLE
# ===== 1. Install =====
# Easiest: IntelliJ IDEA (Community) -> ships with Kotlin.

# CLI (manual):
# macOS:
brew install kotlin
# Linux:
sdk install kotlin

# Verify:
kotlin -version
kotlinc -version

# ===== 2. Hello, Kotlin =====
# hello.kt
fun main() {
    println("hello, Kotlin")
}

# Compile + run:
kotlinc hello.kt -include-runtime -d hello.jar
java -jar hello.jar

# Or scripted (no compile):
kotlinc -script hello.kts
# hello.kts contents:
# println("hello")

# ===== 3. Gradle project =====
mkdir myapp && cd myapp
gradle init --type kotlin-application
# Pick Kotlin DSL + JUnit 5 when prompted.

# src/main/kotlin/Main.kt:
fun main() {
    val name = "World"
    println("Hello, $name!")
}

gradle run

# ===== 4. Modern idioms =====
data class User(val id: Int, val name: String)

fun greet(u: User) = when {
    u.name.isEmpty() -> "Hi there"
    else -> "Hi ${u.name}"
}

val users = listOf(User(1, "Alex"), User(2, "Sam"))
users.filter { it.id > 1 }.forEach(::println)

# ===== 5. Tests (JUnit 5) =====
# src/test/kotlin/MathTest.kt
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*

class MathTest {
    @Test fun adds() { assertEquals(2, 1 + 1) }
}

gradle test

# ===== 6. Android =====
# Android Studio (Kotlin first-class).
# Compose for modern UIs:
@Composable
fun Counter() {
    var count by remember { mutableStateOf(0) }
    Button(onClick = { count++ }) { Text("count: $count") }
}

# ===== 7. Multiplatform (KMP) =====
# Share code across JVM, Android, iOS, JS, Native:
gradle init       # pick 'Kotlin Multiplatform Library'
# expect/actual classes for platform-specific impls.

# ===== Patterns to internalise =====
# - val by default; var only when you must
# - Nullable types in signatures (String?)
# - data class for value carriers
# - Coroutines with structured scopes (never GlobalScope)

# ===== Pitfalls =====
# - !! everywhere -> defeats null safety
# - Mixing Java + Kotlin nullability without @Nullable annotations
# - Long extension chains hiding intent
# - GlobalScope.launch in production code (leak risk)

Why it matters

Install IntelliJ (or Kotlin CLI), scaffold with Gradle, write data classes, run tests. Kotlin is Java with sharp edges removed; the language rewards small reflexes (val, nullable types, data classes, coroutines) and pays back in code that reads like prose.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
# IntelliJ IDEA: New → Kotlin project.
# Or via the CLI:
kotlinc hello.kt -include-runtime -d hello.jar
java -jar hello.jar
Try it Yourself »

Discussion

Loading…