Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟢 Getting Started  ·  Lesson 05

Kotlin Basics for Android

Why Kotlin?

Kotlin is Google's preferred language for Android. Compared with Java it needs less code, prevents many crashes with null safety, and works with every Android library. Everything below runs as plain Kotlin — the outputs shown are real.

Java

  • String name = "Riya";
  • Lots of boilerplate (getters, setters)
  • NullPointerException common

Kotlin

  • val name = "Riya"
  • data class in one line
  • Null safety built in
Same JVM, much shorter code

Where to practise

Use play.kotlinlang.org in the browser, or in Android Studio create a file Practice.kt with a fun main() and click the green ▶ next to it.

Variables: val and var

Kotlin
fun main() {
    val appName = "Student Diary"      // val = cannot change
    var notes = 3                      // var = can change
    notes += 2
    val price: Double = 49.5
    val isPro = false
    println("$appName has $notes notes")
    println("Price: ₹$price, pro = $isPro")
    println("Next year: ${2026 + 1}")
}
Student Diary has 5 notes Price: ₹49.5, pro = false Next year: 2027

val

  • read-only (like final)
  • val appName = "Diary"
  • appName = "X" → error

var

  • can be reassigned
  • var notes = 3
  • notes += 2 → 5
Prefer val

Basic types

TypeExampleUse
Int / Long42 / 1700000000000LCounts / time in millis
Double / Float49.5 / 4.5fPrices / view sizes
Booleantrue, falseisDone, isFavorite
String / Char"Maths" / 'A'Text

Kotlin usually infers the type: val n = 5 is an Int. Convert with "42".toInt(), 5.toString(), 3.7.toInt().

if and when

Kotlin
fun grade(marks: Int): String = when {
    marks >= 90 -> "A+"
    marks >= 75 -> "A"
    marks >= 60 -> "B"
    marks >= 33 -> "Pass"
    else -> "Fail"
}

fun main() {
    val marks = 78
    if (marks >= 33) println("Passed") else println("Failed")
    println("Grade: ${grade(marks)}")

    val day = 3
    val name = when (day) {
        1 -> "Monday"
        2 -> "Tuesday"
        3 -> "Wednesday"
        else -> "Other day"
    }
    println(name)
}
Passed Grade: A Wednesday

Loops and ranges

Kotlin
fun main() {
    for (i in 1..5) print("$i ")
    println()
    for (i in 10 downTo 0 step 5) print("$i ")
    println()
    val subjects = listOf("Maths", "Physics", "English")
    for ((index, s) in subjects.withIndex()) println("${index + 1}. $s")
    var tries = 0
    while (tries < 3) { tries++ }
    println("tries = $tries")
}
1 2 3 4 5 10 5 0 1. Maths 2. Physics 3. English tries = 3

Lists and maps

Kotlin
fun main() {
    val subjects = listOf("Maths", "Physics", "English")          // read-only
    val notes = mutableListOf("Homework")                           // can change
    notes.add("Revision")
    notes.remove("Homework")
    println(subjects.size)
    println(notes)

    val marks = mapOf("Maths" to 92, "Physics" to 81, "English" to 74)
    println(marks["Maths"])
    for ((subject, m) in marks) println("$subject → $m")

    val high = marks.filter { it.value >= 80 }.keys
    println(high)
    println(marks.values.average())
}
3 [Revision] 92 Maths → 92 Physics → 81 English → 74 [Maths, Physics] 82.33333333333333
marks map3 entriesfilter { value >= 80 }.keys[Maths, Physics]
Collection functions chain together

Functions

Kotlin
fun greet(name: String, city: String = "Aligarh"): String {
    return "Namaste $name from $city"
}

fun square(n: Int) = n * n          // single-expression function

fun percent(obtained: Int, total: Int = 100): Double = obtained * 100.0 / total

fun main() {
    println(greet("Riya"))
    println(greet("Aman", city = "Delhi"))   // named argument
    println(square(7))
    println("%.1f%%".format(percent(425, 500)))
}
Namaste Riya from Aligarh Namaste Aman from Delhi 49 85.0%

Where you will use this in Android

Kotlin – inside an app
// The same Kotlin inside an Activity
val count = notes.size                                   // val
binding.tvTitle.text = "You have $count notes"           // string template
val color = when (note.priority) {                       // when
    2 -> R.color.priority_high
    0 -> R.color.priority_low
    else -> R.color.priority_medium
}
val pending = notes.filter { !it.isDone }                // collections + lambda

Common mistakes

  • Reassigning a val → "Val cannot be reassigned".
  • Adding to listOf() → use mutableListOf().
  • "5" + 3 gives "53" (text) — convert first: "5".toInt() + 3.
  • 1..5 includes 5; use 1 until 5 to stop at 4.

Summary

  • val (fixed) and var (changeable); types are inferred.
  • when replaces switch and returns a value.
  • for (i in 1..5), listOf, mapOf, filter, map.
  • Functions with default and named arguments.
✅ Practice

Write a function result(marks: List<Int>) that prints the total, the percentage and the grade using when. Test it with listOf(78, 85, 91, 66, 72).

Frequently Asked Questions

When should I use val and when var?
Use val by default. Switch to var only if the value really needs to change later. Fewer changing values means fewer bugs.
Is when the same as switch?
It replaces switch but is more powerful: it can check ranges and conditions, and it returns a value so you can assign it to a variable.
What is the difference between listOf and mutableListOf?
listOf creates a read-only list. mutableListOf creates a list you can add to and remove from.
← Android Tutorial (Kotlin)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicKotlin OOP, Null Safety & Lambdas Your progress: 5 / 43 (12%) · Lesson 6 / 43 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free