🟢 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
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
Basic types
| Type | Example | Use |
|---|---|---|
| Int / Long | 42 / 1700000000000L | Counts / time in millis |
| Double / Float | 49.5 / 4.5f | Prices / view sizes |
| Boolean | true, false | isDone, 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
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 + lambdaCommon mistakes
- Reassigning a
val→ "Val cannot be reassigned". - Adding to
listOf()→ usemutableListOf(). "5" + 3gives "53" (text) — convert first:"5".toInt() + 3.1..5includes 5; use1 until 5to stop at 4.
Summary
val(fixed) andvar(changeable); types are inferred.whenreplaces 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.
