Kotlin — Cheat Sheet

Tags: kotlin, jvm, android, coroutines, backend

Level: intermediate

TL;DR: A modern, statically typed language targeting the JVM, fully interoperable with Java, focusing on safety, conciseness, and asynchronous programming via coroutines.

Key concepts

Statically typed language with robust type inference

Built-in null safety distinguishes between nullable and non-nullable types

Data classes automatically provide boilerplate methods like equals and copy

Extension functions add behavior to existing classes without modifying inheritance

Coroutines simplify asynchronous and non-blocking code execution natively

Smart casts automatically handle safe type casting after explicit type checks

Classes and methods are final by default requiring the open keyword for inheritance

First-class support for higher-order functions and lambdas

Typical questions and ready answers

Q: How does Kotlin handle null pointer exceptions?R: Kotlin makes types non-nullable by default. For nullable types, I use safe calls (?.) and the Elvis operator (?:) to handle them safely.

Q: What is the purpose of the inline keyword?R: It tells the compiler to inline the function bytecode at the call site. I use it to reduce memory overhead with higher-order functions.

Q: Explain how coroutines differ from traditional threads.R: Coroutines are lightweight and do not map directly to OS threads. I can run thousands of coroutines concurrently without blocking the underlying thread.

Pitfalls and common mistakes

Abusing the !! not-null assertion operator, which bypasses safety checks and causes runtime crashes.

Forgetting that companion objects are initialized when the class is loaded, potentially impacting application startup time.

Creating memory leaks by holding context or view references inside long-running background coroutines.

Snippets and commands

// Data class example
data class User(val id: Int, val name: String)

// Extension function
fun String.isEmailValid(): Boolean {
    return this.contains("@")
}

// Coroutine scope launch
viewModelScope.launch {
    val data = fetchNetworkData()
    processData(data)
}

// Elvis operator usage
val inputLength = textInput?.length ?: 0
Jarvis Interviews
Jarvis