Kotlin Interview Questions
1. val vs var vs const val?
val is read-only (set once at runtime); var is mutable; const val is a compile-time constant (top level or in an object; primitives and String only).
2. How does Kotlin handle null safety?
Types are non-null by default; ? makes them nullable. Use ?., ?:, let and smart casts. !! can still throw an NPE.
3. What is a data class?
A class for holding data, which generates equals, hashCode, toString, copy and componentN() (destructuring).
4. == vs ===?
== compares content (calls equals); === compares references.
5. let vs apply vs also vs run vs with?
They differ in it/this and in whether they return the lambda result or the object. apply configures; also adds side effects; ?.let handles nulls.
6. lateinit vs lazy?
lateinit var is a non-null var assigned later (check with ::x.isInitialized); by lazy is a val computed once, on first access, thread-safe by default.
7. What are sealed classes?
A restricted class hierarchy; when over them is exhaustive. They're ideal for UI states and results.
8. What is a coroutine? launch vs async?
A lightweight, suspendable computation. launch is fire-and-forget (returns a Job); async returns a Deferred to await().
9. object vs companion object?
object is a singleton; a companion object holds class-level members (like static).
10. What are extension functions?
They add functions to existing types without inheritance; they're resolved statically.
11. inline functions?
They copy the function body (and lambdas) into the call site, avoiding lambda allocation. reified type parameters need inline.
12. List vs MutableList?
List is a read-only interface; MutableList adds add/remove.
💡 Back each answer with a one-line example from real Android code.
Example
import kotlin.properties.Delegates
const val API_VERSION = 3 // compile-time constant
class Screen {
lateinit var title: String // set later
val heavy by lazy { println(" computing heavy…"); 42 }
var clicks: Int by Delegates.observable(0) { _, old, new -> println(" clicks $old → $new") }
fun hasTitle() = this::title.isInitialized
}
inline fun <reified T> List<Any>.only(): List<T> = filterIsInstance<T>()
fun main() {
val a = String(charArrayOf('h', 'i'))
val b = "hi"
println("== ${a == b}, === ${a === b}") // true, false
val s = Screen()
println("title initialised? ${s.hasTitle()}")
s.title = "Home"
println("title = ${s.title}")
println("heavy = ${s.heavy}, again = ${s.heavy}") // computed once
s.clicks++; s.clicks++
val mixed: List<Any> = listOf(1, "two", 3.0, "four", 5)
println(mixed.only<String>()) // [two, four] — reified generics
println("API v$API_VERSION")
val readOnly: List<Int> = mutableListOf(1, 2)
println(readOnly is MutableList<*>) // true: read-only view, not immutable!
}