Chapter 3: Kotlin Basics
Kotlin Basics! This is where the fun really starts. Up until now, we’ve set up the tools and run a “Hello World” that Android Studio gave us for free. Now we’re going to write real Kotlin code ourselves, understand why it’s so loved, and build simple logic that makes apps smart.
Imagine we’re in a small café in Airoli — I’m your teacher, whiteboard in front, and you’re typing along in Android Studio. We’ll go slow, with tons of examples, analogies, common mistakes (especially for folks coming from Java or other languages), and little exercises at the end.
Quick note on version (Jan 27, 2026): We’re using Kotlin 2.3.0 (released Dec 2025), which is the latest stable. Android Studio Otter 3 ships with great support for it. All examples here work perfectly in your project.
1. Variables & Data Types (The Building Blocks)
In Kotlin, variables are like labeled boxes where you store data.
Two main kinds:
- val → Immutable (read-only, like final in Java). Use this most of the time — safer!
- var → Mutable (can change later).
Kotlin has type inference — you often don’t need to write the type; it guesses from the value.
Basic types (similar to Java but nicer):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
fun main() { // We'll use main() for quick tests — later in Android we'll use Composables // Numbers val age: Int = 28 // Integer (whole number) val height: Double = 5.9 // Decimal (floating point) val pi: Float = 3.14f // Float needs 'f' at end val bigNumber: Long = 1_000_000_000L // Long needs 'L'; underscores for readability // Text val name = "Webliance" // String (inferred) val initial = 'W' // Char (single quote) // Truth values val isLearningKotlin = true // Boolean // Printing (like console.log) println("Hello, $name! You are $age years old.") // String interpolation with $ // Output: Hello, Webliance! You are 28 years old. } |
String interpolation magic (one of Kotlin’s best features):
|
0 1 2 3 4 5 6 7 8 9 |
val city = "Airoli" val message = "Living in $city is awesome! Population approx ${200_000 + 50000}" // Expression inside ${} println(message) // → Living in Airoli is awesome! Population approx 250000 |
Common mistake: Forgetting to use val first → always prefer val unless you really need to change it.
2. Operators (Math & Comparisons)
Same as most languages, but clean:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
val a = 10 val b = 3 println(a + b) // 13 println(a - b) // 7 println(a * b) // 30 println(a / b) // 3 (integer division) println(a % b) // 1 (remainder) println(a > b) // true println(a == b) // false println(a != b) // true // Compound assignment var score = 50 score += 10 // score = score + 10 → 60 score *= 2 // 120 |
Logical operators:
|
0 1 2 3 4 5 6 7 8 9 10 11 |
val hasPhone = true val hasLaptop = false if (hasPhone && hasLaptop) { println("Tech pro!") } // AND if (hasPhone || hasLaptop) { println("At least one!") } // OR if (!hasLaptop) { println("Need laptop?") } // NOT |
3. Control Flow (Decisions & Loops)
if / else — works as expression (can return value!):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
val temperature = 32 val feeling = if (temperature > 30) { "Too hot! Need AC in Airoli summer" } else if (temperature < 20) { "Chilly! Grab a jacket" } else { "Perfect Mumbai weather" } println(feeling) // → Too hot! Need AC in Airoli summer |
when — Kotlin’s super-powered switch (best feature!):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
val day = 3 // 1=Monday, etc. when (day) { 1 -> println("Monday blues") 2 -> println("Tuesday grind") 3, 4 -> println("Mid-week hustle") // Multiple values in 5..7 -> println("Weekend vibes!") // Range else -> println("Invalid day") } // → Mid-week hustle |
Loops:
- for (most common for ranges/collections):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
for (i in 1..5) { // 1 to 5 inclusive println("Count: $i") } // 1 2 3 4 5 for (i in 5 downTo 1 step 2) { // Down, step by 2 println(i) // 5 3 1 } |
- while / do-while:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var count = 0 while (count < 3) { println("Learning Kotlin: $count") count++ } do { println("This runs at least once") } while (false) |
4. Functions (Reusable Code Blocks)
Functions in Kotlin are concise.
Basic:
|
0 1 2 3 4 5 6 7 8 9 10 |
fun greet(name: String) { // No return type needed if Unit (void) println("Namaste, $name from Airoli!") } greet("Webliance") // → Namaste, Webliance from Airoli! |
With return:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun add(a: Int, b: Int): Int { // Return type explicit return a + b } // Single-expression function (super clean!) fun multiply(a: Int, b: Int) = a * b println(add(5, 7)) // 12 println(multiply(3, 4)) // 12 |
Default & named arguments:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
fun buildMessage(name: String = "Guest", city: String = "Mumbai"): String { return "Hello $name from $city!" } println(buildMessage()) // Hello Guest from Mumbai! println(buildMessage(city = "Airoli")) // Hello Guest from Airoli! println(buildMessage("Rohan", "Navi Mumbai")) |
5. Null Safety (Kotlin’s Superpower — No More NPEs!)
Kotlin prevents null pointer exceptions at compile time.
- Types are non-null by default:
|
0 1 2 3 4 5 6 7 |
var name: String = "Webliance" // name = null // Compile error! Good! |
- Nullable with ?:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var nickname: String? = null // Can be null // Safe access println(nickname?.length) // null if nickname is null (safe call) // Elvis operator (default value) val length = nickname?.length ?: 0 // If null, use 0 // Let (smart cast after check) nickname?.let { println("Nickname length: ${it.length}") // 'it' is non-null here } |
6. Collections (Lists, Maps, Sets)
Kotlin has powerful, immutable-first collections.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// Immutable List val fruits = listOf("Apple", "Banana", "Mango") // Preferred // Mutable val veggies = mutableListOf("Onion", "Tomato") veggies.add("Potato") println(fruits[1]) // Banana println(fruits.size) // 3 // Loop with index for ((index, fruit) in fruits.withIndex()) { println("$index: $fruit") } // Map val capitals = mapOf( "India" to "New Delhi", "Maharashtra" to "Mumbai" ) println(capitals["Maharashtra"]) // Mumbai // Filter, map (functional style) val expensiveFruits = fruits.filter { it.length > 5 } println(expensiveFruits) // [Banana, Mango] |
Hands-on: Simple Kotlin Exercises (Do These Now!)
Open Android Studio → Your HelloWebliance project → Create a new Kotlin file (right-click kotlin folder → New → Kotlin Class/File) → Name it KotlinPlayground.kt
Paste and run these one by one (add fun main() around each exercise):
- Basic variables & string:
Kotlin01234567891011fun main() {val name = "Webliance"val age = 28val isFromAiroli = trueprintln("I am $name, $age years old, from Airoli: $isFromAiroli")}
- When expression:
Kotlin0123456789101112131415fun main() {val trafficLight = "Red"val action = when (trafficLight) {"Red" -> "Stop""Yellow" -> "Slow down""Green" -> "Go"else -> "Invalid"}println("Light: $trafficLight → $action")}
- Function with default param:
Kotlin012345678910fun welcome(name: String = "Student", city: String = "Airoli") = "Welcome $name to Kotlin in $city!"fun main() {println(welcome())println(welcome("Rohan"))}
- Null safety challenge:
Kotlin0123456789101112fun main() {var email: String? = null // Simulate missing data// email = "webliance@example.com" // Try uncommentingval display = email?.uppercase() ?: "No email provided"println(display)}
- Collection fun:
Kotlin012345678910fun main() {val numbers = listOf(1, 2, 3, 4, 5, 10)val evens = numbers.filter { it % 2 == 0 }println("Even numbers: $evens") // [2, 4, 10]}
Run them by right-clicking the file → Run ‘KotlinPlaygroundKt.main()’
Play around! Change values, break things, see errors — that’s how you learn.
Whew — that’s Kotlin basics covered in depth! You now have the tools to think logically in code.
Questions? Stuck on an exercise? Want to add one of these to your Compose app (like show name in Text)? Tell me — next chapter we’ll make your app interactive with state & buttons. You’re killing it! Keep typing, keep experimenting. 🚀💻
