Swipe left or tap Next ▶ to turn the page.
Select any text to highlight it or add a note. Tap a diagram to enlarge it.
Kotlin Basics: val/var, Null Safety, Types, Control Flow, Functions and Collections
- ✔ Explain how Kotlin code becomes an Android app and why Google prefers Kotlin
- ✔ Choose between val and var and pick the right basic type without implicit conversions
- ✔ Use ?., ?:, !!, let and smart casts to write null-safe code
- ✔ Write if/when expressions, ranges, loops, functions and collection pipelines and predict their output
Why Kotlin, and how your code reaches the phone
In almost every Android technical round, the first few questions are about Kotlin itself, so a clear picture of what Kotlin is gives you a confident start.
Kotlin is a modern, statically typed language created by JetBrains. In 2019 Google announced that Android development would be "Kotlin-first", which means new Android libraries, samples and documentation are written with Kotlin in mind. Java still works on Android, and both languages can live in one project, but a fresher applying for an Android role today is expected to know Kotlin.
Statically typed means the compiler knows the type of every variable before the program runs. If you try to put text into a number variable, the build fails on your laptop instead of the app crashing on a user's phone.
From .kt file to running app
The Kotlin compiler (kotlinc) turns .kt files into JVM bytecode (.class files), the same format Java produces. For Android, the build tools then convert this bytecode into DEX (Dalvik Executable) format, package it into an APK or app bundle, and the phone runs it on ART, the Android Runtime.
flowchart LR A[Main.kt] -->|kotlinc| B[.class bytecode] J[Old.java] -->|javac| B B -->|d8 / R8| C[classes.dex] C --> D[APK / AAB] D --> E[ART on the phone]
Because Kotlin and Java both end up as bytecode, Kotlin can call Java libraries and Java can call Kotlin code. This is called interoperability, and it is a favourite interview word.
Your first program
fun main() {
println("Namaste, Android!")
println("2 + 3 = ${2 + 3}")
}
Namaste, Android!
2 + 3 = 5
No class wrapper, no public static void, no semicolons: a top-level fun main() is enough.
Question: which step turns
.classbytecode into the format ART runs?kotlinconly produces.classfiles, so it is not the answer.The dexer (d8, or R8 when shrinking is on) converts
.classto.dex.Answer: the d8/R8 step that produces DEX.
val and var: read-only versus changeable
Choosing val by default is the single habit interviewers notice first in your Kotlin code, because it prevents a whole family of bugs.
Kotlin has two keywords to declare a variable:
| Keyword | Meaning | Can you reassign? |
|---|---|---|
val |
value, read-only reference | No |
var |
variable | Yes |
fun main() {
val city = "Pune"
var score = 10
score = score + 5
println("$city $score")
}
Pune 15
If you write city = "Delhi" the compiler stops with the error Val cannot be reassigned.
Read-only is not the same as "deep" immutable
A val only fixes the reference. If the object itself can change, you can still change it through a val:
fun main() {
val marks = mutableListOf(70, 80)
marks.add(90)
println(marks)
}
[70, 80, 90]
The label marks always points to the same list, but the list grew. This surprises many freshers.
const val
For a compile-time constant (a primitive or String) at top level or inside an object, write const val MAX_USERS = 100. A normal val can hold a value computed at run time.
Code:
val a = 5thena++.a++meansa = a + 1, which is a reassignment.ais aval, so reassignment is not allowed.Answer: compile error, "Val cannot be reassigned".
Code:
val v = mutableListOf("a"), thenv.add("b"), then printv.size.addchanges the list object, not the referencev.The list now has two items.
Answer: prints 2.
Which line will NOT compile?
y is a val, so assigning 4 to it is a reassignment, which is not allowed. The other lines either use var or only change the contents of a mutable list.
Basic types and type inference
Output questions love to test exact type sizes and what happens when you mix Int with Long or Double, so know this table cold.
Every value looks like an object (5.toString() works), but the compiler still uses fast primitives underneath.
| Type | Size | Example |
|---|---|---|
Byte |
8 bits | val b: Byte = 10 |
Short |
16 bits | val s: Short = 300 |
Int |
32 bits | val i = 42 |
Long |
64 bits | val l = 42L |
Float |
32 bits | val f = 2.5f |
Double |
64 bits | val d = 2.5 |
Char |
16 bits | val c = 'K' |
Boolean |
true/false | val ok = true |
Type inference
You rarely need to write the type. The compiler infers it from the value:
val n = 10is anInt.val big = 3_000_000_000is aLong, because the number does not fit in anInt.val price = 99.5is aDouble(decimal literals are Double by default).val rate = 7.5fis aFloatbecause of thefsuffix.
Underscores in numbers (1_00_000) are only for readability. They do not change the value.
No silent widening
Java lets you assign an int to a long silently. Kotlin does not. You must convert explicitly:
fun main() {
val i: Int = 500
val l: Long = i.toLong()
val d = i.toDouble() / 3
println(l)
println("%.2f".format(d))
}
500
166.67
Writing val l: Long = i is a compile error: Type mismatch. The same rule covers comparisons: with val big: Long = 9 and val small = 9, the check big == small does not compile ("Operator '==' cannot be applied to 'Long' and 'Int'"). Convert one side first: big == small.toLong(). The conversion functions are toByte(), toShort(), toInt(), toLong(), toFloat(), toDouble() and toString().
val x = 2_147_483_648.Int.MAX_VALUEis 2,147,483,647, so this literal is one more than the largest Int.The compiler picks the next type that fits.
Answer:
Long.
Keep going with the full course
Day 1 has 21 pages. You have read the first 3.
See what's inside →