Kotlin143 exercises

Kotlin Exercises with Answers

Practise Kotlin with 143 interactive exercises: multiple choice, fill-in-the-blank, output prediction and debugging. Every exercise gives instant feedback, a hint and the full solution.

Score0/ 143

1Introduction

Read the lesson
Fill in the blankseasyIntroduction

Complete the program so it prints Hi.

 main() {
    ("Hi")
}
Predict the outputeasyIntroduction

What does this print?

fun main() {
    print("A")
    print("B")
    println("C")
}
Predict the outputmediumIntroduction

What does this print?

fun main() {
    println("2 + 2")
    println(2 + 2)
}
Multiple choicemediumIntroduction

Which file extension do Kotlin source files use?

Multiple choicehardIntroduction

Why can Kotlin programs use Java libraries?

2Variables & Types

Read the lesson
Fill in the blankseasyVariables & Types

Complete the code so count can be changed later.

 count = 0
count = 5
Predict the outputeasyVariables & Types

What type does Kotlin infer for val x = 4.0?

Predict the outputmediumVariables & Types

What does this print?

var a = 5
val b = a
a = 9
println(b)
Multiple choicemediumVariables & Types

Which line converts "7" into a number safely, without crashing on bad text?

Multiple choicehardVariables & Types

Where can const val be declared?

3Numbers & Operators

Read the lesson
Fill in the blankseasyNumbers & Operators

Complete the code so it prints the remainder of 17 divided by 5.

println(17  5)
Predict the outputeasyNumbers & Operators

What does println(9 / 2) print?

Predict the outputmediumNumbers & Operators

What does this print?

var x = 10
x -= 3
x *= 2
println(x)
Multiple choicemediumNumbers & Operators

Which expression is true only when age is from 13 to 19?

Multiple choicehardNumbers & Operators

How do you show 2.5 as "2.50"?

Fill in the blankseasyStrings

Complete the template so it prints "Hello, Ada".

val name = "Ada"
println("Hello, ")
Predict the outputeasyStrings

What does println("Kotlin".length) print?

Predict the outputmediumStrings

What does this print?

val s = "banana"
println(s.substring(1, 4))
Multiple choicemediumStrings

Which line prints "Total: 15"?

Predict the outputhardStrings

What does this print?

val parts = "a-b-c".split("-")
println(parts.joinToString(""))

5Null Safety

Read the lesson
Fill in the blankseasyNull Safety

Complete the declaration so middleName can be null.

var middleName: String = null
Predict the outputeasyNull Safety

What does this print?

val city: String? = null
println(city ?: "Unknown")
Predict the outputmediumNull Safety

What does this print?

val word: String? = "kotlin"
println(word?.uppercase()?.length)
Multiple choicemediumNull Safety

What does s?.let { println(it) } do when s is null?

Multiple choicehardNull Safety

Why is !! usually a warning sign in code reviews?

Fill in the blankseasyif & when

Complete the expression so it returns "Even" or "Odd".

val kind = if (n % 2 == 0) "Even"  "Odd"
Predict the outputeasyif & when

What does this print?

val x = 7
when (x) {
    1, 3, 5, 7, 9 -> println("odd")
    else -> println("even")
}
Predict the outputmediumif & when

What does this print?

val temp = 18
val advice = when {
    temp > 25 -> "hot"
    temp > 15 -> "mild"
    temp > 5 -> "cool"
    else -> "cold"
}
println(advice)
Multiple choicemediumif & when

Which when branch matches every number from 10 to 20?

Multiple choicehardif & when

What value does this block produce?

val result = if (true) {
    println("checking")
    42
} else {
    0
}

7Loops & Ranges

Read the lesson
Fill in the blankseasyLoops & Ranges

Complete the loop so it prints 10, 9, 8 ... 1.

for (i in 10  1) println(i)
Predict the outputeasyLoops & Ranges

How many numbers does for (i in 0 until 4) loop over?

Predict the outputmediumLoops & Ranges

What does this print?

for (i in 1..10 step 3) print("$i ")
Multiple choicemediumLoops & Ranges

Which loop always runs its body at least once?

Predict the outputhardLoops & Ranges

What does this print?

var total = 0
for (n in 1..6) {
    if (n == 4) continue
    total += n
}
println(total)
Fill in the blankseasyFunctions

Complete the function so it returns the square of n.

 square(n: Int): Int = n * n
Predict the outputeasyFunctions

What does this print?

fun greet(name: String = "friend") = "Hi, $name"
println(greet())
Predict the outputmediumFunctions

What does this print?

fun box(w: Int = 1, h: Int = 1) = w * h
println(box(h = 5))
Multiple choicemediumFunctions

What is the return type of a function that only prints?

Multiple choicehardFunctions

Which call is valid for fun send(to: String, subject: String = "Hi", urgent: Boolean = false)?

Fill in the blankseasyLists

Complete the code so the list can have items added.

val cart = ("bread")
cart.add("eggs")
Predict the outputeasyLists

What does this print?

val xs = listOf("a", "b", "c", "d")
println(xs[2])
Predict the outputmediumLists

What does this print?

val xs = mutableListOf(5, 3, 8)
xs.add(0, 1)
xs.removeAt(2)
println(xs)
Multiple choicemediumLists

What's the difference between sort() and sorted()?

Multiple choicehardLists

Why can val basket = mutableListOf<String>() still have items added?

10Maps & Sets

Read the lesson
Fill in the blankseasyMaps & Sets

Complete the line so it sets the price of juice to 1.9.

prices[""] = 1.9
Predict the outputeasyMaps & Sets

What does this print?

val m = mapOf("a" to 1, "b" to 2)
println(m["c"])
Predict the outputmediumMaps & Sets

What does this print?

val s = mutableSetOf(1, 2, 3)
s.add(2)
s.add(4)
println(s.size)
Multiple choicemediumMaps & Sets

Which expression gives every item in set a that isn't in set b?

Predict the outputhardMaps & Sets

What does this print?

val counts = mutableMapOf<Char, Int>()
for (c in "banana") counts[c] = (counts[c] ?: 0) + 1
println(counts)

11Collection Operations

Read the lesson
Fill in the blankseasyCollection Operations

Complete the code so it keeps only numbers greater than 10.

val big = numbers. { it > 10 }
Predict the outputeasyCollection Operations

What does this print?

println(listOf(1, 2, 3).map { it * it })
Predict the outputmediumCollection Operations

What does this print?

val words = listOf("apple", "kiwi", "banana", "fig")
println(words.filter { it.length > 3 }.map { it.uppercase() })
Multiple choicemediumCollection Operations

Which returns a Map from each category to its products?

Predict the outputhardCollection Operations

What does this print?

val (even, odd) = (1..6).partition { it % 2 == 0 }
println(even.sum() - odd.sum())
Fill in the blankseasyLambdas

Complete the lambda so it returns its number plus one.

val inc: (Int) -> Int = {  + 1 }
Predict the outputeasyLambdas

What does this print?

val f = { x: Int -> x * 3 }
println(f(4))
Predict the outputmediumLambdas

What does this print?

fun applyTwice(x: Int, f: (Int) -> Int) = f(f(x))
println(applyTwice(2) { it * 5 })
Multiple choicemediumLambdas

What does the type (String) -> Boolean describe?

Predict the outputhardLambdas

What does this print?

fun adder(n: Int): (Int) -> Int = { it + n }
val add5 = adder(5)
val add10 = adder(10)
println(add5(1) + add10(1))

13Classes & Objects

Read the lesson
Fill in the blankseasyClasses & Objects

Complete the constructor so name becomes a read-only property.

class City( name: String)
Predict the outputeasyClasses & Objects

What does this print?

class Counter(var n: Int = 0) {
    fun up() { n++ }
}
val c = Counter(5)
c.up(); c.up()
println(c.n)
Multiple choicemediumClasses & Objects

What does private set on a property do?

Multiple choicemediumClasses & Objects

Where should you check that constructor values are valid?

Predict the outputhardClasses & Objects

What does this print?

class Box(val w: Int, val h: Int) {
    val area get() = w * h
}
val b = Box(3, 4)
println(b.area + Box(2, 2).area)

14Data Classes

Read the lesson
Fill in the blankseasyData Classes

Complete the declaration so Point gets a generated toString and equals.

 class Point(val x: Int, val y: Int)
Predict the outputeasyData Classes

What does this print?

data class Pet(val name: String, val age: Int)
println(Pet("Rex", 3))
Predict the outputmediumData Classes

What does this print?

data class Size(val w: Int, val h: Int)
val a = Size(2, 3)
val b = a.copy(h = 9)
println("${a.h} ${b.h}")
Multiple choicemediumData Classes

Which properties does a data class use for equals and toString?

Multiple choicehardData Classes

Which is the best fit for a regular class rather than a data class?

15Inheritance & Interfaces

Read the lesson
Fill in the blankseasyInheritance & Interfaces

Complete the class so other classes can inherit from it.

 class Vehicle(val wheels: Int)
Multiple choiceeasyInheritance & Interfaces

How many classes can a Kotlin class extend?

Predict the outputmediumInheritance & Interfaces

What does this print?

open class A { open fun hi() = "A" }
class B : A() { override fun hi() = "B" + super.hi() }
println(B().hi())
Multiple choicemediumInheritance & Interfaces

What must a subclass of an abstract class do?

Multiple choicehardInheritance & Interfaces

Why does Kotlin make classes final by default?

16Objects & Companions

Read the lesson
Fill in the blankseasyObjects & Companions

Complete the declaration so Config is a singleton.

 Config {
    val apiUrl = "https://api.example.com"
}
Multiple choiceeasyObjects & Companions

How do you call create in a companion object of class User?

Predict the outputmediumObjects & Companions

What does this print?

object Counter { var n = 0 }
Counter.n++
Counter.n += 5
println(Counter.n)
Multiple choicemediumObjects & Companions

Why combine a private constructor with a companion factory function?

Multiple choicehardObjects & Companions

When is a top-level function better than an object holding the function?

17Enums & Sealed Classes

Read the lesson
Fill in the blankseasyEnums & Sealed Classes

Complete the declaration of an enum for directions.

 class Direction { NORTH, EAST, SOUTH, WEST }
Predict the outputeasyEnums & Sealed Classes

What does this print?

enum class Size { S, M, L }
println(Size.L.ordinal)
Multiple choicemediumEnums & Sealed Classes

When should you use a sealed class instead of an enum?

Multiple choicemediumEnums & Sealed Classes

Why can a when over a sealed interface skip else?

Predict the outputhardEnums & Sealed Classes

What does this print?

enum class Op(val f: (Int, Int) -> Int) {
    ADD({ a, b -> a + b }), MUL({ a, b -> a * b })
}
println(Op.entries.map { it.f(3, 4) })

18Exceptions

Read the lesson
Fill in the blankseasyExceptions

Complete the code so the clean-up message always prints.

try {
    work()
} catch (e: Exception) {
    println("Failed")
}  {
    println("Cleaned up")
}
Predict the outputeasyExceptions

What does this print?

val x = try { "5".toInt() } catch (e: Exception) { -1 }
println(x)
Multiple choicemediumExceptions

Which exception does require(false) { "bad" } throw?

Predict the outputmediumExceptions

What does this print?

val r = runCatching { listOf(1, 2)[5] }
println(r.getOrElse { 0 })
Multiple choicehardExceptions

Does Kotlin force you to catch exceptions that a function might throw?

19Extension Functions

Read the lesson
Fill in the blankseasyExtension Functions

Complete the extension so it can be called as "hi".shout().

fun .shout() = uppercase() + "!"
Predict the outputeasyExtension Functions

What does this print?

fun Int.isEven() = this % 2 == 0
println(7.isEven())
Predict the outputmediumExtension Functions

What does this print?

val String.lastChar: Char get() = this[length - 1]
println("Kotlin".lastChar)
Multiple choicemediumExtension Functions

Can an extension function read a class's private properties?

Multiple choicehardExtension Functions

A class has a member fun greet() and there's also an extension fun MyClass.greet(). Which runs for obj.greet()?

Fill in the blankseasyGenerics

Complete the declaration of a generic class that holds one item of any type.

class Box<>(val item: T)
Multiple choiceeasyGenerics

Where does a generic function declare its type parameter?

Predict the outputmediumGenerics

What does this print?

fun <T> twice(x: T): List<T> = listOf(x, x)
println(twice("ha"))
Multiple choicemediumGenerics

What does T : Comparable<T> mean?

Multiple choicehardGenerics

Why can a List<Cat> be passed where List<Animal> is expected, but not a MutableList<Cat> for MutableList<Animal>?

21Scope Functions

Read the lesson
Fill in the blankseasyScope Functions

Complete the code so the block runs only when name isn't null.

name?. { println("Hi, $it") }
Multiple choiceeasyScope Functions

Which scope function returns the object itself and refers to it as this?

Predict the outputmediumScope Functions

What does this print?

val n = 5.let { it * 2 }.also { println("got $it") }
println(n)
Predict the outputmediumScope Functions

What does this print?

val x = "abc".takeIf { it.length > 5 } ?: "short"
println(x)
Multiple choicehardScope Functions

Which is the best choice for logging a value in the middle of a chain without changing it?

22Coroutines

Read the lesson
Fill in the blankseasyCoroutines

Complete the declaration so the function can call delay.

 fun loadData(): String {
    delay(500)
    return "data"
}
Multiple choiceeasyCoroutines

Which builder returns a result you can await?

Predict the outputmediumCoroutines

What does this print?

fun main() = runBlocking {
    launch { delay(50); print("B") }
    print("A")
}
Multiple choicemediumCoroutines

Which dispatcher suits reading a large file?

Multiple choicehardCoroutines

Two async calls each take one second. When does awaiting both take about one second in total?

Fill in the blankseasyFlows

Complete the flow builder so it sends the value 42 to collectors.

val f = flow {
    (42)
}
Multiple choiceeasyFlows

When does the code inside flow { } run?

Predict the outputmediumFlows

What does this print?

runBlocking {
    flowOf(1, 2, 3, 4).filter { it % 2 == 0 }.map { it * 10 }.collect { print("$it ") }
}
Multiple choicemediumFlows

What's the key difference between StateFlow and a normal Flow?

Multiple choicehardFlows

Which operator should a search box use so it only searches after the user stops typing for a moment?

24Files & I/O

Read the lesson
Fill in the blankseasyFiles & I/O

Complete the line that adds text to the end of a file.

File("log.txt").("Saved\n")
Multiple choiceeasyFiles & I/O

What does File("a.txt").writeText("hi") do to an existing file?

Multiple choicemediumFiles & I/O

Which is best for counting lines in a 5 GB file?

Multiple choicemediumFiles & I/O

What does use { } guarantee?

Predict the outputhardFiles & I/O

A file contains "a\nb\nc\n". What does readLines().size return?

Fill in the blankseasyTesting

Complete the annotation that marks a function as a test.


fun `adds two numbers`() {
    assertEquals(4, 2 + 2)
}
Multiple choiceeasyTesting

In assertEquals(a, b), which is the expected value?

Multiple choicemediumTesting

How do you check that a call throws IllegalArgumentException?

Multiple choicemediumTesting

Why use a fake repository in tests?

Multiple choicehardTesting

What does runTest do with delay(5_000)?

26Arrays and primitive arrays

Read the lesson
Multiple choicemediumArrays and primitive arrays

A matrix must have independent mutable rows. Which initializer fits?

27Packages and visibility

Read the lesson
Multiple choicemediumPackages and visibility

A count should be readable publicly but writable only by its class. Which design fits?

28Type checks and casts

Read the lesson
Multiple choicemediumType checks and casts

An unknown value must be a list containing only strings. Which plan is appropriate?

29Delegated properties

Read the lesson
Multiple choicemediumDelegated properties

A service is required for every valid instance and is available at construction. Which approach is usually clearest?

30Interface delegation

Read the lesson
Multiple choicemediumInterface delegation

A wrapper must validate one operation before forwarding. Which implementation fits?

31Nested and inner classes

Read the lesson
Multiple choicemediumNested and inner classes

A receipt label must never change after purchase. Which model best expresses that requirement?

32Inline functions and returns

Read the lesson
Multiple choicemediumInline functions and returns

A lambda is invoked through a nested Runnable and must not return from its caller. Which modifier expresses that restriction?

33Operator overloading

Read the lesson
Multiple choicemediumOperator overloading

A business operation sends a payment and can fail in several ways. What API is usually clearer?

34Sequences

Read the lesson
Multiple choicemediumSequences

A sequence may be infinite. Which expression obtains a bounded sample?

35Equality and hashing

Read the lesson
Multiple choicemediumEquality and hashing

Which design best supports changing a customer's display name?

36Regex parsing

Read the lesson
Multiple choicemediumRegex parsing

A captured digit string must represent an Int from 1 through 100. Which approach handles both limits?

37Java interoperability

Read the lesson
Multiple choicemediumJava interoperability

A Java-owned list can change after your adapter returns. What supports a stable snapshot?

38Gradle Kotlin DSL

Read the lesson
Multiple choicemediumGradle Kotlin DSL

Main.kt now declares package shop. Which entry point matches its top-level main?

39JSON serialization

Read the lesson
Multiple choicemediumJSON serialization

A nullable field should accept omission as null. Which declaration states that ordinary policy?

40Dates and time zones

Read the lesson
Multiple choicemediumDates and time zones

Which design makes a due-date test independent of the machine's current day?

41Supervision and cleanup

Read the lesson
Multiple choicemediumSupervision and cleanup

Where should a necessary bounded suspending cleanup run after cancellation?

42Shared state and Mutex

Read the lesson
Multiple choicemediumShared state and Mutex

Which statement accurately describes an in-process Mutex?

43Flow buffering and sharing

Read the lesson
Multiple choicemediumFlow buffering and sharing

A temporary component shares an expensive source. Which design addresses its lifetime?

Next steps