Kotlin quiz – 40 questions with answers
Try it interactively
With scoring, random questions, and saved progress – or go straight to the timed exam with certificate.
Beginner (14 questions)
What happens with this code?
val x = 5
x = 6- x is 6 afterwards
- Compile error: val cannot be reassigned
- Runtime error
- Only a warning
Show answer
Correct: Compile error: val cannot be reassigned
val declares an immutable variable. The compiler rejects a second assignment; for mutable values, use var.
What does 7 / 2 yield for two Int values?
- 3.5
- 3
- 4
- 2
Show answer
Correct: 3
With two Int operands, / is integer division: 3. For 3.5 you need 7 / 2.0.
What does this code print?
val name = "Ada"
println("Hello $name, ${name.length}")- Hello $name, ${name.length}
- Hello Ada, 3
- Hello Ada, name.length
- Hello Ada 3
Show answer
Correct: Hello Ada, 3
In string templates, $name replaces the variable, and ${...} evaluates an expression.
What does this code print?
for (i in 1..3) print(i)- 12
- 123
- 0123
- 321
Show answer
Correct: 123
1..3 is a range that includes both ends: 1, 2, 3.
What does this code print?
for (i in 0 until 3) print(i)- 0123
- 012
- 123
- 01
Show answer
Correct: 012
until excludes the end: 0, 1, 2.
What type does val x = 3.14 have?
- Float
- Double
- Decimal
- Number
Show answer
Correct: Double
Decimal literals are Double by default. For Float you need the suffix f.
What does this code print?
for (i in 10 downTo 1 step 3) print("$i ")- 10 7 4 1
- 10 9 8
- 1 4 7 10
- 10 7 4
Show answer
Correct: 10 7 4 1
Backwards from 10 in steps of three: 10, 7, 4, 1.
Which keyword do you use to define a function in Kotlin?
- function
- def
- fun
- func
Show answer
Correct: fun
In Kotlin, functions begin with fun.
What happens with this code?
val liste = listOf(1, 2, 3)
liste.add(4)- The list contains 4 elements afterwards
- Compile error: List has no add method
- ArrayIndexOutOfBoundsException
- The list is returned unchanged
Show answer
Correct: Compile error: List has no add method
listOf returns a read-only List without add. For changes, use mutableListOf.
What does this code print?
val x = 15
val s = when {
x < 10 -> "small"
x < 20 -> "medium"
else -> "large"
}
println(s)- small
- medium
- large
- medium-large
Show answer
Correct: medium
The first matching when branch wins: 15 < 20 is true, so medium.
What does this code print?
fun gruss(name: String, text: String = "Hi") = "$text $name"
println(gruss("Ada"))- Hi Ada
- Ada Hi
- Ada
- Compile error
Show answer
Correct: Hi Ada
The default value "Hi" is used when no second argument is passed.
How do you write a conditional expression in Kotlin (instead of ? :)?
- a > b ? a : b
- if (a > b) a else b
- a > b then a else b
- a > b ?: a
Show answer
Correct: if (a > b) a else b
if is an expression in Kotlin: val m = if (a > b) a else b. There is no ternary operator.
What does this code print?
val m = mapOf("a" to 1)
println(m["b"])- 0
- null
- KeyNotFoundException error
- An empty string
Show answer
Correct: null
map[key] returns null if the key is missing (the return type is nullable).
What does this code print?
println("5" + 5)- 10
- 55
- "5 5"
- Compile error
Show answer
Correct: 55
String.plus(Any?) appends the value as text: 55.
Intermediate (13 questions)
What does the type String? mean?
- A string that may be empty
- A string that may also be null
- An optional parameter
- A placeholder string
Show answer
Correct: A string that may also be null
The question mark makes the type nullable. Without a question mark, a variable can never be null.
What does this code print?
fun f(s: String?) = s?.length ?: -1
println(f(null))- 0
- -1
- null
- Error
Show answer
Correct: -1
s?.length is null, so the Elvis operator ?: returns -1.
What does the !! operator do?
- It checks for null and returns a default value
- It throws a NullPointerException if the value is null
- It negates a value twice
- It is a safe cast
Show answer
Correct: It throws a NullPointerException if the value is null
x!! asserts that x is not null and otherwise throws a NullPointerException. Use it as rarely as possible.
What does this code print?
data class P(val x: Int, val y: Int)
println(P(1, 2).copy(y = 5))- P(x=1, y=2)
- P(x=1, y=5)
- P(1, 5)
- Compile error
Show answer
Correct: P(x=1, y=5)
copy creates a copy and replaces only the named fields. The data class toString yields P(x=1, y=5).
What does this code print?
data class P(val x: Int)
println((P(1) == P(1)).toString() + " " + (P(1) === P(1)))- true true
- true false
- false false
- false true
Show answer
Correct: true false
== calls equals (for data classes field by field: true), === checks the reference (two objects: false).
What does this code print?
fun String.zweimal() = this + this
println("ab".zweimal())- ab
- abab
- ab ab
- Compile error
Show answer
Correct: abab
The extension function zweimal is defined on String; this is "ab", and the result is abab.
Why can you not simply inherit from a normally declared Kotlin class?
- Because Kotlin has no inheritance
- Because classes are final by default – you need
open - Because only interfaces may be inherited
- Because the constructor has to be private
Show answer
Correct: Because classes are final by default – you need open
In Kotlin, classes and methods are final by default. With open you allow inheritance or overriding.
What does this code print?
println(listOf(1, 2, 3, 4).filter { it % 2 == 0 }.map { it * 10 })- [20, 40]
- [10, 30]
- [2, 4]
- [20, 40, 60, 80]
Show answer
Correct: [20, 40]
filter keeps 2 and 4, map multiplies by 10: [20, 40].
Which scope function returns the object itself and uses this as its context?
- let
- apply
- run
- with
Show answer
Correct: apply
apply configures an object via this and returns it. (also also returns the object, but uses it.)
What does this code print?
val (a, b) = Pair(1, "x")
println("$b$a")- 1x
- x1
- x 1
- Compile error
Show answer
Correct: x1
Destructuring: a = 1, b = "x". The template $b$a yields x1.
Which statement about exceptions in Kotlin is true?
- Checked exceptions must be declared with throws
- Kotlin has no checked exceptions
- try cannot be used as an expression
- catch is mandatory for every try
Show answer
Correct: Kotlin has no checked exceptions
All exceptions in Kotlin are unchecked. try is also an expression and returns a value.
What does this code print?
println(listOf("a", "bb", "cc", "d").groupBy { it.length })- {1=[a, d], 2=[bb, cc]}
- {a=1, bb=2, cc=2, d=1}
- [[a, d], [bb, cc]]
- {1=2, 2=2}
Show answer
Correct: {1=[a, d], 2=[bb, cc]}
groupBy builds a map from key (length) to a list of the matching elements.
What does this code print?
val z = try {
"x".toInt()
} catch (e: NumberFormatException) {
0
}
println(z)- 0
- x
- Compile error: try is not an expression
- The exception terminates the program
Show answer
Correct: 0
toInt throws a NumberFormatException, and the catch branch returns 0. In Kotlin, try is an expression.
Advanced (13 questions)
What does the keyword suspend mean on a function?
- It always runs in a new thread
- It can pause without blocking the thread and can only be called from coroutines or other suspend functions
- It is thread-safe
- It is executed lazily
Show answer
Correct: It can pause without blocking the thread and can only be called from coroutines or other suspend functions
suspend functions can pause at certain points (e.g. delay) and resume later. They can only be called from coroutines.
What is the difference between launch and async?
- No difference
asyncreturns a Deferred with a result that you retrieve viaawait();launchreturns only a Joblaunchis fasterasyncblocks the thread
Show answer
Correct: async returns a Deferred with a result that you retrieve via await(); launch returns only a Job
launch is "fire and forget" (returns a Job), while async returns a Deferred<T> whose result await() provides.
What does structured concurrency guarantee?
- Coroutines always run one after another
- A scope ends only when all its children are done; errors and cancellation are propagated
- Coroutines never use more than one thread
- There are no exceptions in coroutines
Show answer
Correct: A scope ends only when all its children are done; errors and cancellation are propagated
Coroutines belong to a scope: it waits for all children, and cancellation or errors affect the whole hierarchy – so no coroutines get lost.
What is Dispatchers.IO intended for?
- For UI updates
- For blocking input/output such as file or network access
- For compute-intensive calculations
- For execution on the main thread
Show answer
Correct: For blocking input/output such as file or network access
Dispatchers.IO uses a thread pool designed for blocking I/O. For CPU work there is Dispatchers.Default, for UI Dispatchers.Main.
In what order does the output appear?
fun main() = runBlocking {
launch { delay(100); println("B") }
println("A")
}- A, then B
- B, then A
- Only A
- Only B
Show answer
Correct: A, then B
launch starts the coroutine, println("A") continues immediately; B follows after the delay. runBlocking waits for the child.
What happens if a when expression over a sealed interface does not cover a subtype and has no else?
- null is returned at runtime
- Compile error: the when is not exhaustive
- A default value is used
- Only a warning
Show answer
Correct: Compile error: the when is not exhaustive
when as an expression must be exhaustive. For sealed types, the compiler knows all subtypes and reports missing cases.
What does by lazy { ... } do on a property?
- Recomputes the value on every access
- Computes the value on first access and stores it afterwards
- Computes the value on another thread
- Makes the property nullable
Show answer
Correct: Computes the value on first access and stores it afterwards
lazy initializes the value only on first access (thread-safe by default) and returns the same value from then on.
What is printed?
val x by lazy { println("init"); 5 }
println(x + x)- 10
- init, then 10
- init, init, then 10
- Compile error
Show answer
Correct: init, then 10
The initializer runs only once on first access (init), after which the value 5 is fixed: 5 + 5 = 10.
What is reified used for in inline fun <reified T> ...?
- It makes the type parameter nullable
- The type T is preserved at runtime so that
is TorT::classare possible - It makes the function faster
- It forbids inheritance
Show answer
Correct: The type T is preserved at runtime so that is T or T::class are possible
Normally generics are erased at runtime. With inline and reified, the concrete type is inserted into the caller.
What is a value class (with @JvmInline) good for?
- For classes with multiple constructors
- For type-safe wrappers around a single value without (usually) an additional object at runtime
- For singletons
- For classes with inheritance
Show answer
Correct: For type-safe wrappers around a single value without (usually) an additional object at runtime
A value class wraps a value (e.g. UserId(Long)) in its own type and avoids mix-ups, usually without runtime overhead.
What does this code print?
val r = sequenceOf(1, 2, 3, 4)
.map { print("m$it "); it * 2 }
.first { it > 2 }
println(r)- m1 m2 4
- m1 m2 m3 m4 4
- 4
- m2 4
Show answer
Correct: m1 m2 4
Sequences are lazy: element 1 becomes 2 (not > 2), element 2 becomes 4 – first stops. Output m1 m2 4.
What does this code print?
val strings: List<String> = listOf("a")
val anys: List<Any> = strings
println(anys.size)- 1
- Compile error: List<String> is not a List<Any>
- 0
- ClassCastException
Show answer
Correct: 1
List<out E> is covariant: a list of strings is a valid list of Any, because it is only read.
What should you keep in mind with runBlocking?
- It always starts a new thread
- It blocks the calling thread until the coroutine is done – fine for main and tests, not for normal application code
- It cannot be nested
- It replaces async
Show answer
Correct: It blocks the calling thread until the coroutine is done – fine for main and tests, not for normal application code
runBlocking bridges blocking and suspending code, but blocks the thread in the process – avoid it in UI or server code.