How to Pass a Kotlin Interview: Breakdown of Top Questions with Examples
Kotlin has firmly established itself as a modern language for Android development and JVM backend. If you are preparing for a technical interview, it's important not just to know the syntax, but also to understand the language's philosophy: safety, conciseness, and Java compatibility. In this article, we will break down the key questions most often asked in Kotlin interviews, with real code examples.
1. Null Safety: How Kotlin Solves the null Problem
One of Kotlin's main selling points is its built-in protection against NullPointerException. In an interview, you will definitely be asked about nullable and non-null types.
Question: What is the difference between String? and String? How to work safely with nullable?
Answer: The String type guarantees that the variable will never be null. String? allows null. For safe access, the operators ?., ?: (Elvis), and !! (only if you are 100% sure) are used.
fun main() { val name: String? = null // Safe call println(name?.length) // null // Default value val length = name?.length ?: 0 println(length) // 0 // Force unwrap (risk of NPE) // println(name!!.length) // Error!}Additional question: What are lateinit and lazy?
lateinit— for variables that are initialized later (onlyvar).lazy— for delegated initialization (onlyval).
class User { lateinit var email: String val config by lazy { loadConfig() } fun init() { email = "test@example.com" }}2. Coroutines: Asynchrony Without Pain
Coroutines are a must-have for modern Kotlin. Interviewers check understanding of suspend, launch, async, and dispatchers.
Question: What is the difference between launch and async?
Answer: launch starts a coroutine and returns a Job (without a result). async returns a Deferred, from which you can get a result via await().
suspend fun fetchData(): String { delay(1000) return "Data loaded"}
fun main() = runBlocking { // launch: without result val job = launch { println("Task 1 completed") } // async: with result val deferred = async { fetchData() } println(deferred.await()) // "Data loaded" job.join()}Question: What dispatchers (Dispatchers) do you know?
Dispatchers.Main— for UI (Android).Dispatchers.IO— for input/output, network.Dispatchers.Default— for CPU-intensive tasks.Dispatchers.Unconfined— not tied to a specific thread (rarely used).
3. Extension Functions and Sealed Classes: Expanding Capabilities
Kotlin allows adding new functions to existing classes without inheritance. This is often asked in the context of architecture.
Question: What are extension functions? Give an example.
Answer: These are functions that are declared outside a class but are called as its methods. They do not modify the class, but merely add syntactic sugar.
// Extension function for Stringfun String.isEmail(): Boolean { return this.contains("@") && this.contains(".")}
fun main() { val email = "user@example.com" println(email.