Kotlin Basics for Android Beginners — Part 1
Kotlin Basics for Android Beginners — Part 1
This is the Kotlin you need before writing a single line of Android code. If you already know Kotlin, skip ahead to the course. If you don't, read this first — the Android Beginners course assumes everything here.
Variables: val vs var
val name = "Ahmad" // val = read-only, can't be reassigned
var age = 25 // var = mutable, can be reassigned
age = 26 // fine
// name = "Sam" // error: val cannot be reassignedDefault to val everywhere. Only use var when you genuinely need to reassign a variable later — this single habit prevents a huge class of bugs before they happen.
Basic types
val count: Int = 10
val price: Double = 9.99
val isActive: Boolean = true
val label: String = "Hello"Kotlin can usually infer the type, so you rarely need to write : Int explicitly — val count = 10 works identically.
Functions
fun greet(name: String): String {
return "Hello, $name!"
}
// Shorthand for simple functions:
fun greet(name: String) = "Hello, $name!"The $name syntax is called string templates — it inserts the variable's value directly into the string, no concatenation needed.
Control flow
val temperature = 15
if (temperature > 20) {
println("Warm")
} else {
println("Cool")
}
// if as an expression (returns a value):
val label = if (temperature > 20) "Warm" else "Cool"
for (i in 1..5) {
println(i)
}
when (temperature) {
in 0..10 -> println("Cold")
in 11..20 -> println("Cool")
else -> println("Warm")
}when is Kotlin's more powerful version of a switch statement — you'll see it constantly in Android code.
Null safety — Kotlin's biggest difference from Java
var name: String = "Ahmad" // can never be null
var nickname: String? = null // the ? means this CAN be null
// Safe call — returns null instead of crashing if nickname is null
println(nickname?.length)
// Elvis operator — provide a fallback if null
val length = nickname?.length ?: 0This is the single most important Kotlin concept for Android: the compiler forces you to handle the possibility of null at every step, which is exactly what prevents the classic "NullPointerException" crash that used to plague Android apps written in Java.