← Android Developer (Kotlin)
Day 1 · Kotlin Basics: val/var, Null Safety, Types, Control Flow, Functions and Collections
Android Developer (Kotlin) · Crash Course
Day 1

Kotlin Basics: val/var, Null Safety, Types, Control Flow, Functions and Collections

⏱ About 90 minutes · 21 pages
By the end of today you will be able to
  • ✔ 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
  1. Why Kotlin, and how your code reaches the phone
  2. val and var: read-only versus changeable
  3. Basic types and type inference

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.

✍️ Example 1 — Name the stage
  1. Question: which step turns .class bytecode into the format ART runs?

  2. kotlinc only produces .class files, so it is not the answer.

  3. The dexer (d8, or R8 when shrinking is on) converts .class to .dex.

  4. Answer: the d8/R8 step that produces DEX.

Android Developer (Kotlin) · Day 12 / 5

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.

val city = "Pune" "Pune" Label fixed for life var score = 10 10 15 Label can move to new value

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.

✍️ Example 2 — Will it compile?
  1. Code: val a = 5 then a++.

  2. a++ means a = a + 1, which is a reassignment.

  3. a is a val, so reassignment is not allowed.

  4. Answer: compile error, "Val cannot be reassigned".

✍️ Example 3 — val holding a mutable list
  1. Code: val v = mutableListOf("a"), then v.add("b"), then print v.size.

  2. add changes the list object, not the reference v.

  3. The list now has two items.

  4. Answer: prints 2.

🙋 Try it now

Which line will NOT compile?

Android Developer (Kotlin) · Day 13 / 5

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 = 10 is an Int.
  • val big = 3_000_000_000 is a Long, because the number does not fit in an Int.
  • val price = 99.5 is a Double (decimal literals are Double by default).
  • val rate = 7.5f is a Float because of the f suffix.

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().

✍️ Example 4 — Infer the type
  1. val x = 2_147_483_648.

  2. Int.MAX_VALUE is 2,147,483,647, so this literal is one more than the largest Int.

  3. The compiler picks the next type that fits.

  4. Answer: Long.

Android Developer (Kotlin) · Day 14 / 5
Free preview ends here

Keep going with the full course

Day 1 has 21 pages. You have read the first 3.

See what's inside →