Irbisa · Cheatsheet
Kotlin Basics
val/var, types, null safety, control flow, functions, lambdas
What are the advantages of Kotlin over Java for Android, and what are its drawbacks?
What is the difference between
val,varandconst valin Kotlin?val name = "Ada" // type inferred as String// name = "Bob" // compile error: val cannot be reassigned var attempts = 0attempts += 1 // fine…How does null safety work in Kotlin: nullable types,
?.,?:,!!andlet?fun greet(user: User?) { val city = user?.address?.city // String?: null if any link is null val name = user?.name ?: "Guest" // fallback value user?.let { analytics.track(it.id) } // runs only when user != null if (user == null) return…What does
describe(null)print here, line by line?fun describe(name: String?) { println(name?.length) println(name?.length ?: -1) println(name.isNullOrEmpty()) println("Hello, $name") println(name!!.length)} fun main() { describe(null)}lateinitvsby lazy: when do you use each, and how do you check that alateinitproperty is initialized?@AndroidEntryPointclass ProfileActivity : AppCompatActivity() { @Inject lateinit var repo: UserRepository // assigned by Hilt private lateinit var binding: ActivityProfileBinding private val dateFormat by lazy { // created on first use…What is the difference between
==and===in Kotlin?data class User(val id: Int, val name: String) val a = User(1, "Ada")val b = User(1, "Ada")println(a == b) // true: equals() compares propertiesprintln(a === b) // false: two different objects…How does
whenwork as an expression in Kotlin, and when must it be exhaustive?sealed interface UiState { data object Loading : UiState data class Content(val items: List<String>) : UiState data class Error(val message: String) : UiState}…How do ranges work in Kotlin:
..,..<,until,downToandstep?val items = listOf("a", "b", "c") // for (i in 0..items.size) println(items[i]) // wrong: crashes when i == 3for (i in 0..<items.size) println(items[i]) // end excludedfor (i in 0 until items.size) println(items[i]) // same, older spellingfor (i in items.indices) println(items[i])…What are lambdas and higher-order functions in Kotlin, and what does a lambda compile to?
// Higher-order function: takes a function as a parameterfun retry(times: Int, block: () -> Boolean): Boolean { repeat(times) { if (block()) return true } return false}…What does this counter code print, and where does
countlive aftermakeCounter()returns?fun makeCounter(): () -> Int { var count = 0 return { ++count }} fun main() { val first = makeCounter() val second = makeCounter() println(first()) println(first()) println(second())}How do default and named arguments work in Kotlin, and how do they replace the Builder pattern?
data class Request( val url: String, val method: String = "GET", val timeoutMs: Long = 10_000, val headers: Map<String, String> = emptyMap(),)…What is the difference between
ListandMutableList, and between avalmutable list and avarread-only list?class Cart { private val _items = mutableListOf<String>() // mutable inside val items: List<String> get() = _items // read-only outside fun add(item: String) { _items += item }}…What do
map,flatMap,fold,reduce,groupBy,associateBy,partitionandzipdo on a Kotlin collection?data class Order(val id: Int, val user: String, val total: Long, val items: List<String>) val orders = listOf( Order(1, "ada", 300, listOf("pen", "ink")), Order(2, "bob", 0, emptyList()), Order(3, "ada", 150, listOf("paper")),…When do you use an
Arrayinstead of aList, and why doesarrayOf(1, 2) == arrayOf(1, 2)return false?val a = arrayOf(1, 2)val b = arrayOf(1, 2)println(a == b) // false: reference comparisonprintln(a.contentEquals(b)) // trueprintln(a.contentToString()) // [1, 2]println(listOf(1, 2) == listOf(1, 2)) // true…How do destructuring declarations work in Kotlin?
data class Size(val width: Int, val height: Int) val (w, h) = Size(1080, 1920) // component1(), component2() val prices = mapOf("apple" to 3, "pear" to 5)for ((fruit, price) in prices) println("$fruit costs $price")…Why is building a string with
+=in a loop slow, and what do you use instead?// wrong: a new String on every iteration, O(n²) copyingvar csv = ""for (u in users) csv += u.name + "," // right: one bufferval csvFast = buildString {…What are smart casts in Kotlin, when does the compiler refuse them, and how do
asandas?differ?fun describe(x: Any): String { if (x is String) return "text of ${x.length}" // smart cast to String if (x !is Int) return "unknown" return "number ${x + 1}" // smart cast to Int}…Find the bug: a signed-in user who opens the profile for the first time also sees the guest banner.
data class User(val id: String, val name: String) class ProfileScreen { private val lastSeenName = mutableMapOf<String, String>() fun render(user: User?) { user?.let { lastSeenName.put(it.id, it.name) } ?: showGuestBanner() showGreeting(user?.name ?: "guest") } private fun showGuestBanner() = println("Sign in to sync your progress") private fun showGreeting(name: String) = println("Hello, $name")}Can a
valproperty return a different value each time you read it?class Basket { private val items = mutableListOf<Item>() val size: Int get() = items.size // no backing field, recomputed val isEmpty: Boolean get() = size == 0…Find the bug: after one user logs out and another signs in, every request fails with 401 until the app is restarted.
data class Request(val path: String, val headers: Map<String, String>) class Session { var token: String? = null // replaced on every login} class ApiClient(private val session: Session) { // one instance for the app private val authHeader by lazy { "Bearer ${session.token}" } fun request(path: String): Request = Request(path, headers = mapOf("Authorization" to authHeader))}Does Kotlin have primitive types, and when does an
Intget boxed?val count: Int = 42 // int on the JVMval maybe: Int? = 42 // java.lang.Integer: nullable means boxedval list: List<Int> = listOf(1, 2) // List<Integer>: generics always boxval raw = IntArray(1_000) // int[], no boxing // val total: Long = count // compile error: no implicit widening…What are
Any,UnitandNothingin Kotlin, and how many instances of each can exist?fun log(message: String) { // returns Unit implicitly println(message)}val onDone: () -> Unit = { log("done") } fun fail(message: String): Nothing = throw IllegalArgumentException(message)…Does Kotlin have checked exceptions, and how do you signal and handle failures instead?
sealed interface LoginResult { data class Success(val user: User) : LoginResult data object WrongPassword : LoginResult data object Offline : LoginResult}…What does this
forEachcode print, and how do you make it skip only the blank item?fun printVisible(items: List<String>) { items.forEach { if (it.isBlank()) return println(it) } println("done")} fun main() { printVisible(listOf("a", " ", "b"))}