KtKotlin

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
  1. x is 6 afterwards
  2. Compile error: val cannot be reassigned
  3. Runtime error
  4. 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?

  1. 3.5
  2. 3
  3. 4
  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}")
  1. Hello $name, ${name.length}
  2. Hello Ada, 3
  3. Hello Ada, name.length
  4. 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)
  1. 12
  2. 123
  3. 0123
  4. 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)
  1. 0123
  2. 012
  3. 123
  4. 01
Show answer

Correct: 012

until excludes the end: 0, 1, 2.

What type does val x = 3.14 have?

  1. Float
  2. Double
  3. Decimal
  4. 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 ")
  1. 10 7 4 1
  2. 10 9 8
  3. 1 4 7 10
  4. 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?

  1. function
  2. def
  3. fun
  4. 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)
  1. The list contains 4 elements afterwards
  2. Compile error: List has no add method
  3. ArrayIndexOutOfBoundsException
  4. 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)
  1. small
  2. medium
  3. large
  4. 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"))
  1. Hi Ada
  2. Ada Hi
  3. Ada
  4. 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 ? :)?

  1. a > b ? a : b
  2. if (a > b) a else b
  3. a > b then a else b
  4. 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"])
  1. 0
  2. null
  3. KeyNotFoundException error
  4. 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)
  1. 10
  2. 55
  3. "5 5"
  4. Compile error
Show answer

Correct: 55

String.plus(Any?) appends the value as text: 55.

Intermediate (13 questions)

What does the type String? mean?

  1. A string that may be empty
  2. A string that may also be null
  3. An optional parameter
  4. 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))
  1. 0
  2. -1
  3. null
  4. Error
Show answer

Correct: -1

s?.length is null, so the Elvis operator ?: returns -1.

What does the !! operator do?

  1. It checks for null and returns a default value
  2. It throws a NullPointerException if the value is null
  3. It negates a value twice
  4. 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))
  1. P(x=1, y=2)
  2. P(x=1, y=5)
  3. P(1, 5)
  4. 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)))
  1. true true
  2. true false
  3. false false
  4. 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())
  1. ab
  2. abab
  3. ab ab
  4. 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?

  1. Because Kotlin has no inheritance
  2. Because classes are final by default – you need open
  3. Because only interfaces may be inherited
  4. 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 })
  1. [20, 40]
  2. [10, 30]
  3. [2, 4]
  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?

  1. let
  2. apply
  3. run
  4. 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")
  1. 1x
  2. x1
  3. x 1
  4. 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?

  1. Checked exceptions must be declared with throws
  2. Kotlin has no checked exceptions
  3. try cannot be used as an expression
  4. 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. {1=[a, d], 2=[bb, cc]}
  2. {a=1, bb=2, cc=2, d=1}
  3. [[a, d], [bb, cc]]
  4. {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)
  1. 0
  2. x
  3. Compile error: try is not an expression
  4. 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?

  1. It always runs in a new thread
  2. It can pause without blocking the thread and can only be called from coroutines or other suspend functions
  3. It is thread-safe
  4. 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?

  1. No difference
  2. async returns a Deferred with a result that you retrieve via await(); launch returns only a Job
  3. launch is faster
  4. async blocks 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?

  1. Coroutines always run one after another
  2. A scope ends only when all its children are done; errors and cancellation are propagated
  3. Coroutines never use more than one thread
  4. 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?

  1. For UI updates
  2. For blocking input/output such as file or network access
  3. For compute-intensive calculations
  4. 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")
}
  1. A, then B
  2. B, then A
  3. Only A
  4. 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?

  1. null is returned at runtime
  2. Compile error: the when is not exhaustive
  3. A default value is used
  4. 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?

  1. Recomputes the value on every access
  2. Computes the value on first access and stores it afterwards
  3. Computes the value on another thread
  4. 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)
  1. 10
  2. init, then 10
  3. init, init, then 10
  4. 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> ...?

  1. It makes the type parameter nullable
  2. The type T is preserved at runtime so that is T or T::class are possible
  3. It makes the function faster
  4. 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?

  1. For classes with multiple constructors
  2. For type-safe wrappers around a single value without (usually) an additional object at runtime
  3. For singletons
  4. 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)
  1. m1 m2 4
  2. m1 m2 m3 m4 4
  3. 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. 1
  2. Compile error: List<String> is not a List<Any>
  3. 0
  4. 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?

  1. It always starts a new thread
  2. It blocks the calling thread until the coroutine is done – fine for main and tests, not for normal application code
  3. It cannot be nested
  4. 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.