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.
Topic All topics Introduction Variables & Types Numbers & Operators Strings Null Safety if & when Loops & Ranges Functions Lists Maps & Sets Collection Operations Lambdas Classes & Objects Data Classes Inheritance & Interfaces Objects & Companions Enums & Sealed Classes Exceptions Extension Functions Generics Scope Functions Coroutines Flows Files & I/O Testing Arrays and primitive arrays Packages and visibility Type checks and casts Delegated properties Interface delegation Nested and inner classes Inline functions and returns Operator overloading Sequences Equality and hashing Regex parsing Java interoperability Gradle Kotlin DSL JSON serialization Dates and time zones Supervision and cleanup Shared state and Mutex Flow buffering and sharing
All types Fill in the blanks Predict the output Multiple choice
Any level Easy Medium Hard
Score 0 / 143
fun main ( ) {
print ( "A" )
print ( "B" )
println ( "C" )
}
A ABC B A, B and C on separate lines C A B C D CBA
print doesn't add a new line, so all three letters appear together.
Show answer
fun main ( ) {
println ( "2 + 2" )
println ( 2 + 2 )
}
A 4 and 4 B 2 + 2 twice C 2 + 2, then 4 D An error
Quoted text is printed as written; the unquoted sum is calculated.
Show answer
Which file extension do Kotlin source files use?
A .kotlin B .kts only C .java D .kt
.kts is for Kotlin scripts, such as Gradle build files; normal source files use .kt.
Show answer
Why can Kotlin programs use Java libraries?
A Kotlin is a newer name for Java B Kotlin compiles to JVM bytecode, the same format Java uses C Kotlin converts Java code to Kotlin automatically D It can't
Both run on the Java Virtual Machine, so they work together.
Show answer
Complete the code so count can be changed later.
count = 0
count = 5
var allows reassignment; val doesn't.
Check answer Show solution
What type does Kotlin infer for val x = 4.0?
A Int B Double C Float D String
A number with a decimal point is a Double by default.
Show answer
var a = 5
val b = a
a = 9
println ( b)
A 5 B 9 C 14 D An error
b got the value 5 when it was created; changing a later doesn't affect it.
Show answer
Which line converts "7" into a number safely, without crashing on bad text?
A "7".toInt() B Int("7") C (Int) "7" D "7".toIntOrNull()
toIntOrNull returns null for invalid text.
Show answer
Where can const val be declared?
A Inside any function B Only inside main C At the top level of a file, or inside an object D Anywhere a var can go
const values must be known at compile time and can't be local variables.
Show answer
Complete the code so it prints the remainder of 17 divided by 5.
println ( 17 5 )
% gives the remainder: 2.
Check answer Show solution
What does println(9 / 2) print?
A 4.5 B 5 C 4 D 4.0
Both values are Ints, so the decimals are dropped.
Show answer
var x = 10
x -= 3
x *= 2
println ( x)
A 17 B 20 C 7 D 14
10 minus 3 is 7, and 7 times 2 is 14.
Show answer
Which expression is true only when age is from 13 to 19?
A age >= 13 && age <= 19 B age > 13 || age < 19 C age >= 13 || age <= 19 D !(age == 13)
&& requires both conditions to be true.
Show answer
How do you show 2.5 as "2.50"?
A 2.5.toString(2) B round(2.5, 2) C "%.2f".format(2.5) D 2.5.toInt()
The format string %.2f always shows two decimal places.
Show answer
Complete the template so it prints "Hello, Ada".
val name = "Ada"
println ( "Hello, ")
$name inserts the variable's value into the string.
Check answer Show solution
What does println("Kotlin".length) print?
A 5 B 7 C 6 D Kotlin
K-o-t-l-i-n is six characters.
Show answer
val s = "banana"
println ( s. substring ( 1 , 4 ) )
A ban B anan C ana D nan
Indexes 1, 2 and 3: a, n, a. The end index isn't included.
Show answer
Which line prints "Total: 15"?
A println("Total: $a + $b") with a = 10, b = 5 B println("Total: " + a + b) with a = 10, b = 5 C println('Total: ${a + b}') D println("Total: ${a + b}") with a = 10, b = 5
The expression must be inside ${ } to be calculated.
Show answer
val parts = "a-b-c" . split ( "-" )
println ( parts. joinToString ( "" ) )
A abc B a-b-c C [a, b, c] D a b c
split removes the dashes, and joining with an empty separator puts the letters together.
Show answer
Complete the declaration so middleName can be null.
var middleName: String = null
Adding ? makes the type nullable.
Check answer Show solution
val city: String ? = null
println ( city ? : "Unknown" )
A null B An empty line C Unknown D An error
Elvis uses the right side when the left side is null.
Show answer
val word: String ? = "kotlin"
println ( word? . uppercase ( ) ? . length )
A KOTLIN B null C An error D 6
word isn't null, so both safe calls run and give the length 6.
Show answer
What does s?.let { println(it) } do when s is null?
A Nothing: the block doesn't run B Prints null C Throws an exception D Prints an empty line
The safe call skips let entirely for null.
Show answer
Why is !! usually a warning sign in code reviews?
A It's slow B It crashes with a NullPointerException if the value is null, undoing Kotlin's protection C It only works on Strings D It makes the variable immutable
Prefer safe calls, Elvis, if checks or let.
Show answer
Complete the expression so it returns "Even" or "Odd".
val kind = if ( n % 2 == 0 ) "Even" "Odd"
An if expression needs an else branch.
Check answer Show solution
val x = 7
when ( x) {
1 , 3 , 5 , 7 , 9 -> println ( "odd" )
else -> println ( "even" )
}
A odd B even C 7 D Nothing
7 matches one of the listed values.
Show answer
val temp = 18
val advice = when {
temp > 25 -> "hot"
temp > 15 -> "mild"
temp > 5 -> "cool"
else -> "cold"
}
println ( advice)
A hot B mild C mild and cool D cool
Only the first true branch runs.
Show answer
Which when branch matches every number from 10 to 20?
A 10 - 20 -> B 10, 20 -> C is 10..20 -> D in 10..20 ->
in checks membership in a range.
Show answer
What value does this block produce?
val result = if ( true ) {
println ( "checking" )
42
} else {
0
}
A "checking" B 42 C Unit D 0
The last expression in the chosen block is its value.
Show answer
Complete the loop so it prints 10, 9, 8 ... 1.
for ( i in 10 1 ) println ( i)
downTo creates a range that counts down.
Check answer Show solution
How many numbers does for (i in 0 until 4) loop over?
A 5 B 3 C 4 D 0
0, 1, 2 and 3; until excludes 4.
Show answer
for ( i in 1 . . 10 step 3 ) print ( "$i " )
A 1 3 6 9 B 3 6 9 C 1 4 7 D 1 4 7 10
Start at 1 and add 3 each time; 10 is included.
Show answer
Which loop always runs its body at least once?
A for B while C do-while D repeat(0)
do-while checks its condition after the body.
Show answer
var total = 0
for ( n in 1 . . 6 ) {
if ( n == 4 ) continue
total += n
}
println ( total)
A 21 B 6 C 10 D 17
1 + 2 + 3 + 5 + 6 = 17; 4 is skipped.
Show answer
Complete the function so it returns the square of n.
square ( n: Int ) : Int = n * n
fun declares a function; = gives a single-expression body.
Check answer Show solution
fun greet ( name: String = "friend" ) = "Hi, $name"
println ( greet ( ) )
A Hi, B Hi, name C An error D Hi, friend
The default value is used when no argument is given.
Show answer
fun box ( w: Int = 1 , h: Int = 1 ) = w * h
println ( box ( h = 5 ) )
A 1 B 6 C An error D 5
w keeps its default of 1, and h is 5.
Show answer
What is the return type of a function that only prints?
A Void B Nothing C Unit D Null
Unit means "no useful value" and can be left out.
Show answer
Which call is valid for fun send(to: String, subject: String = "Hi", urgent: Boolean = false)?
A send("sam@example.com", urgent = true) B send(urgent = true) C send("sam@example.com", true) D send(subject = "Hi", "sam@example.com")
to has no default and must be given; the named argument skips subject.
Show answer
Fill in the blankseasy Lists Complete the code so the list can have items added.
val cart = ( "bread" )
cart. add ( "eggs" )
mutableListOf creates a list that can change.
Check answer Show solution
Predict the outputeasy Lists
val xs = listOf ( "a" , "b" , "c" , "d" )
println ( xs[ 2 ] )
A c B b C d D An error
Indexes start at 0, so index 2 is the third item.
Show answer
Predict the outputmedium Lists
val xs = mutableListOf ( 5 , 3 , 8 )
xs. add ( 0 , 1 )
xs. removeAt ( 2 )
println ( xs)
A [1, 5, 3] B [5, 3, 8, 1] C [1, 3, 8] D [1, 5, 8]
After adding at 0 the list is [1, 5, 3, 8]; removing index 2 removes the 3.
Show answer
Multiple choicemedium Lists What's the difference between sort() and sorted()?
A sort is faster B sorted only works on numbers C sort changes a mutable list in place; sorted returns a new list D There's none
The -ed versions leave the original untouched.
Show answer
Why can val basket = mutableListOf<String>() still have items added?
A val doesn't work with lists B val stops the variable pointing to a different list, but the mutable list's contents can change C It's a bug D Lists are always mutable
val is about the reference, not the contents.
Show answer
Complete the line so it sets the price of juice to 1.9.
prices[ " "] = 1.9
map[key] = value adds or updates an entry.
Check answer Show solution
val m = mapOf ( "a" to 1 , "b" to 2 )
println ( m[ "c" ] )
A null B 0 C An exception D c
Missing keys return null.
Show answer
val s = mutableSetOf ( 1 , 2 , 3 )
s. add ( 2 )
s. add ( 4 )
println ( s. size )
A 5 B 4 C 3 D 2
2 is already there, so only 4 is added.
Show answer
Which expression gives every item in set a that isn't in set b?
A a union b B a intersect b C a subtract b D b subtract a
subtract removes b's items from a.
Show answer
val counts = mutableMapOf < Char , Int > ( )
for ( c in "banana" ) counts[ c] = ( counts[ c] ? : 0 ) + 1
println ( counts)
A {b=1, a=1, n=1} B {a=3, n=2, b=1} C {b=1, a=3, n=2} D [b, a, n]
Each letter is counted, in the order it first appears.
Show answer
Complete the code so it keeps only numbers greater than 10.
val big = numbers. { it > 10 }
filter keeps items for which the block returns true.
Check answer Show solution
println ( listOf ( 1 , 2 , 3 ) . map { it * it } )
A [2, 4, 6] B 14 C [1, 2, 3] D [1, 4, 9]
map squares each number.
Show answer
val words = listOf ( "apple" , "kiwi" , "banana" , "fig" )
println ( words. filter { it. length > 3 } . map { it. uppercase ( ) } )
A [APPLE, KIWI, BANANA] B [APPLE, KIWI, BANANA, FIG] C [APPLE, BANANA] D [apple, kiwi, banana]
fig is filtered out; the rest are uppercased.
Show answer
Which returns a Map from each category to its products?
A products.associate { it.category } B products.groupBy { it.category } C products.partition { it.category } D products.map { it.category }
groupBy collects items with the same key into lists.
Show answer
val ( even, odd) = ( 1 . . 6 ) . partition { it % 2 == 0 }
println ( even. sum ( ) - odd. sum ( ) )
A 0 B -3 C 3 D 21
2 + 4 + 6 is 12 and 1 + 3 + 5 is 9.
Show answer
Complete the lambda so it returns its number plus one.
val inc: ( Int ) -> Int = { + 1 }
it is the implicit name of a single parameter.
Check answer Show solution
val f = { x: Int -> x * 3 }
println ( f ( 4 ) )
A 7 B 12 C 43 D An error
The lambda multiplies its argument by 3.
Show answer
fun applyTwice ( x: Int , f: ( Int ) -> Int ) = f ( f ( x) )
println ( applyTwice ( 2 ) { it * 5 } )
A 10 B 25 C 50 D 7
2 times 5 is 10, then 10 times 5 is 50.
Show answer
What does the type (String) -> Boolean describe?
A A String that may be a Boolean B A function that takes a String and returns a Boolean C A Boolean variable named String D A list of Strings
Inputs are in brackets, the output after the arrow.
Show answer
fun adder ( n: Int ) : ( Int ) -> Int = { it + n }
val add5 = adder ( 5 )
val add10 = adder ( 10 )
println ( add5 ( 1 ) + add10 ( 1 ) )
A 17 B 12 C 16 D 2
6 plus 11; each lambda remembers its own n.
Show answer
Complete the constructor so name becomes a read-only property.
class City ( name: String )
val in the constructor creates a read-only property.
Check answer Show solution
class Counter ( var n: Int = 0 ) {
fun up ( ) { n++ }
}
val c = Counter ( 5 )
c. up ( ) ; c. up ( )
println ( c. n )
A 7 B 5 C 2 D 0
It starts at 5 and is increased twice.
Show answer
What does private set on a property do?
A Hides the property completely B Makes it a constant C Deletes the setter D Lets anyone read it but only the class change it
The getter stays public.
Show answer
Where should you check that constructor values are valid?
A In main B In an init block, with require C In a getter D In toString
init runs every time an object is created.
Show answer
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 )
A 7 B 12 C 16 D 11
12 plus 4.
Show answer
Complete the declaration so Point gets a generated toString and equals.
class Point ( val x: Int , val y: Int )
The data keyword generates the useful functions.
Check answer Show solution
data class Pet ( val name: String , val age: Int )
println ( Pet ( "Rex" , 3 ) )
A Pet@1b6d3586 B Rex 3 C Pet(name=Rex, age=3) D {name=Rex, age=3}
The generated toString lists the properties.
Show answer
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}" )
A 9 9 B 3 3 C An error D 3 9
copy creates a new object; a is unchanged.
Show answer
Which properties does a data class use for equals and toString?
A Only the properties declared in the primary constructor B All properties in the class C Only var properties D Only the first property
Properties in the class body are ignored.
Show answer
Which is the best fit for a regular class rather than a data class?
A A Point with x and y B A Money value with an amount and currency C A BankAccount whose balance changes and which has its own identity D A User loaded from an API
Two accounts with equal balances are still different accounts.
Show answer
Complete the class so other classes can inherit from it.
class Vehicle ( val wheels: Int )
Classes are final unless marked open.
Check answer Show solution
How many classes can a Kotlin class extend?
A One B Two C Unlimited D None
A class can extend one class but implement many interfaces.
Show answer
open class A { open fun hi ( ) = "A" }
class B : A ( ) { override fun hi ( ) = "B" + super . hi ( ) }
println ( B ( ) . hi ( ) )
A A B B C BA D AB
B's version adds "B" before the parent's result.
Show answer
What must a subclass of an abstract class do?
A Nothing special B Provide an implementation for every abstract member C Mark itself abstract D Call super in every method
Otherwise it must be abstract too.
Show answer
Why does Kotlin make classes final by default?
A To save memory B To prevent fragile, accidental inheritance; you opt in with open when a class is designed for it C Because Kotlin doesn't support inheritance D To make classes faster to create
It encourages interfaces and composition.
Show answer
Complete the declaration so Config is a singleton.
Config {
val apiUrl = "https://api.example.com"
}
object declares a class with exactly one instance.
Check answer Show solution
How do you call create in a companion object of class User?
A User().create() B companion.create() C new User.create() D User.create()
Companion members are called on the class name.
Show answer
object Counter { var n = 0 }
Counter . n ++
Counter . n += 5
println ( Counter . n )
A 6 B 0 C 5 D 1
There's one shared instance, so both changes apply to the same n.
Show answer
Why combine a private constructor with a companion factory function?
A To make objects faster B So every object is created through the factory, which can validate or return null C To allow inheritance D To make the class a singleton
Outside code can't bypass the checks.
Show answer
When is a top-level function better than an object holding the function?
A Never B When you need a singleton C When implementing an interface D For a simple utility with no shared state, like formatting a price
Kotlin allows functions outside classes.
Show answer
Complete the declaration of an enum for directions.
class Direction { NORTH, EAST, SOUTH, WEST }
enum class defines a fixed set of constants.
Check answer Show solution
enum class Size { S, M, L }
println ( Size . L . ordinal )
A 2 B 3 C L D 1
ordinal counts from 0.
Show answer
When should you use a sealed class instead of an enum?
A When each case carries different data, such as Success(items) and Error(message) B When there are more than three options C When you need a String value D Never
Enum constants all share the same shape.
Show answer
Why can a when over a sealed interface skip else?
A else is never allowed B The compiler knows every possible subtype, so it can check all are handled C Sealed types can't be null D It only works with one case
That's what makes it exhaustive.
Show answer
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 ) } )
A [7, 7] B [ADD, MUL] C [12, 7] D [7, 12]
Each constant stores its own function.
Show answer
Complete the code so the clean-up message always prints.
try {
work ( )
} catch ( e: Exception ) {
println ( "Failed" )
} {
println ( "Cleaned up" )
}
finally runs whether or not an exception happened.
Check answer Show solution
val x = try { "5" . toInt ( ) } catch ( e: Exception ) { - 1 }
println ( x)
A -1 B "5" C An error D 5
Parsing succeeds, so the try block's value is used.
Show answer
Which exception does require(false) { "bad" } throw?
A IllegalArgumentException B IllegalStateException C NullPointerException D NumberFormatException
require is for checking arguments; check throws IllegalStateException.
Show answer
val r = runCatching { listOf ( 1 , 2 ) [ 5 ] }
println ( r. getOrElse { 0 } )
A 2 B null C 0 D An IndexOutOfBoundsException
runCatching captures the exception and getOrElse supplies 0.
Show answer
Does Kotlin force you to catch exceptions that a function might throw?
A Yes, like Java's checked exceptions B No, Kotlin has no checked exceptions C Only for IOException D Only in main
It's your responsibility to handle the ones that matter.
Show answer
Complete the extension so it can be called as "hi".shout().
fun . shout ( ) = uppercase ( ) + "!"
The receiver type goes before the function name.
Check answer Show solution
fun Int . isEven ( ) = this % 2 == 0
println ( 7 . isEven ( ) )
A true B 7 C false D An error
this is 7, which isn't even.
Show answer
val String . lastChar : Char get ( ) = this [ length - 1 ]
println ( "Kotlin" . lastChar )
A K B n C 6 D An error
The extension property returns the final character.
Show answer
Can an extension function read a class's private properties?
A Yes, always B Only for data classes C Only if it's infix D No, only its public members
Extensions don't break encapsulation.
Show answer
A class has a member fun greet() and there's also an extension fun MyClass.greet(). Which runs for obj.greet()?
A The extension B The member function C Both D It doesn't compile
Members always win over extensions with the same signature.
Show answer
Complete the declaration of a generic class that holds one item of any type.
class Box < > ( val item: T)
T is the conventional name for a type parameter.
Check answer Show solution
Where does a generic function declare its type parameter?
A After the parameters B Before the function name, as in fun <T> f(x: T) C In the return type only D It doesn't need one
fun <T> comes first.
Show answer
fun < T> twice ( x: T) : List < T> = listOf ( x, x)
println ( twice ( "ha" ) )
A [ha, ha] B haha C [ha] D An error
T is inferred as String and a list of two items is returned.
Show answer
What does T : Comparable<T> mean?
A T must be exactly Comparable B T is optional C T can be any type that can be compared with itself D T must be a number
It's an upper bound.
Show answer
Why can a List<Cat> be passed where List<Animal> is expected, but not a MutableList<Cat> for MutableList<Animal>?
A Lists are faster B MutableList isn't generic C List only produces items (out), so it's safe; a MutableList could have a Dog added to it D It's a compiler bug
Producer out, consumer in.
Show answer
Complete the code so the block runs only when name isn't null.
name? . { println ( "Hi, $it" ) }
?.let runs the block with it as the non-null value.
Check answer Show solution
Which scope function returns the object itself and refers to it as this?
A apply B let C also D run
apply is ideal for configuring an object.
Show answer
val n = 5 . let { it * 2 } . also { println ( "got $it" ) }
println ( n)
A got 5, then 5 B got 10, then 10 C 10 only D got 10, then 5
let returns 10; also prints it and passes 10 on.
Show answer
val x = "abc" . takeIf { it. length > 5 } ? : "short"
println ( x)
A abc B null C true D short
takeIf returns null when the condition is false, so Elvis gives "short".
Show answer
Which is the best choice for logging a value in the middle of a chain without changing it?
A also B let C run D with
also passes the original object on.
Show answer
Complete the declaration so the function can call delay.
fun loadData ( ) : String {
delay ( 500 )
return "data"
}
Only suspend functions (or coroutines) can call delay.
Check answer Show solution
Which builder returns a result you can await?
A launch B runBlocking C async D delay
async returns a Deferred; launch returns a Job.
Show answer
fun main ( ) = runBlocking {
launch { delay ( 50 ) ; print ( "B" ) }
print ( "A" )
}
A BA B A only C B only D AB
The launched coroutine suspends at delay, so A prints first; runBlocking waits for B.
Show answer
Which dispatcher suits reading a large file?
A Dispatchers.IO B Dispatchers.Main C Dispatchers.Unconfined D No dispatcher
IO is for network and disk work.
Show answer
Two async calls each take one second. When does awaiting both take about one second in total?
A Never B When they use Thread.sleep C When they're inside separate runBlocking calls D When both async blocks are started before either is awaited
Starting both first lets them overlap.
Show answer
Fill in the blankseasy Flows Complete the flow builder so it sends the value 42 to collectors.
val f = flow {
( 42 )
}
emit sends a value from inside the flow builder.
Check answer Show solution
When does the code inside flow { } run?
A As soon as the flow is created B Only once ever C On a background thread automatically D When it's collected, separately for each collector
Flows are cold.
Show answer
Predict the outputmedium Flows
runBlocking {
flowOf ( 1 , 2 , 3 , 4 ) . filter { it % 2 == 0 } . map { it * 10 } . collect { print ( "$it " ) }
}
A 20 40 B 10 20 30 40 C 2 4 D 10 30
The even numbers 2 and 4 are kept and multiplied by 10.
Show answer
Multiple choicemedium Flows What's the key difference between StateFlow and a normal Flow?
A StateFlow is faster B StateFlow is hot and always has a current value that new collectors receive immediately C StateFlow can't be collected D StateFlow only holds Strings
Normal flows are cold and have no current value.
Show answer
Which operator should a search box use so it only searches after the user stops typing for a moment?
A take B zip C reduce D debounce
debounce waits for a pause between values.
Show answer
Complete the line that adds text to the end of a file.
File ( "log.txt" ) . ( "Saved\n" )
appendText adds to the end instead of replacing the file.
Check answer Show solution
What does File("a.txt").writeText("hi") do to an existing file?
A Adds hi to the end B Nothing C Throws an exception D Replaces its contents with hi
Use appendText to add instead.
Show answer
Which is best for counting lines in a 5 GB file?
A readText() B useLines { it.count() } C readLines() D readBytes()
useLines processes one line at a time.
Show answer
What does use { } guarantee?
A The resource is closed when the block ends, even if an exception happens B The file is read faster C The file is created if missing D Errors are ignored
It's Kotlin's try-with-resources.
Show answer
A file contains "a\nb\nc\n". What does readLines().size return?
A 4 B 1 C 3 D 6
The trailing newline doesn't produce an extra empty line.
Show answer
Complete the annotation that marks a function as a test.
fun `adds two numbers`( ) {
assertEquals ( 4 , 2 + 2 )
}
@Test tells the test runner to run the function.
Check answer Show solution
In assertEquals(a, b), which is the expected value?
A a, the first argument B b, the second argument C Either D Neither
Expected first, actual second.
Show answer
How do you check that a call throws IllegalArgumentException?
A assertEquals(IllegalArgumentException, call()) B assertFailsWith<IllegalArgumentException> { call() } C try { call() } catch (e: Exception) { } D @Test(expected = Exception)
assertFailsWith also returns the exception for further checks.
Show answer
Why use a fake repository in tests?
A Fakes are required by kotlin.test B It makes the app faster C It hides bugs D It gives fast, predictable data without a real database or network
Tests stay quick and reliable.
Show answer
What does runTest do with delay(5_000)?
A Skips it using virtual time, so the test finishes almost instantly B Waits five real seconds C Throws an exception D Runs it on a background thread
That's why runTest is used for coroutine tests.
Show answer
A matrix must have independent mutable rows. Which initializer fits?
A Create one IntArray and put that same instance in every row B Use one integer variable for the entire matrix C Array(3) { IntArray(2) }
The initializer creates a separate row array for each outer position, avoiding accidental shared-row updates.
Show answer
A count should be readable publicly but writable only by its class. Which design fits?
A A public mutable field with no checks B A private class whose state is never read C A public property with private set and checked mutation methods
Restricting the setter preserves observation while making the permitted changes explicit.
Show answer
An unknown value must be a list containing only strings. Which plan is appropriate?
A Check List<*> and validate each element B Assume List<*> guarantees string elements C Cast to List<String> without examining input
The outer list shape and the element contract need separate validation because generic arguments are erased.
Show answer
A service is required for every valid instance and is available at construction. Which approach is usually clearest?
A Leave it lateinit and hope a caller assigns it B Hide its absence behind a lazy fallback C Require it as a constructor dependency
Constructor injection establishes the required dependency when the object becomes usable.
Show answer
A wrapper must validate one operation before forwarding. Which implementation fits?
A Trust that overriding an unrelated property secures every call B Override the exposed operation and call a private delegate after validation C Expose the delegate publicly so callers can bypass checks
The policy belongs on the actual public operation being controlled.
Show answer
A receipt label must never change after purchase. Which model best expresses that requirement?
A An inner helper reading the current mutable catalog title B A global variable updated on every catalog rename C A separate value storing the approved title snapshot
Historical output should use a stable captured value rather than a live owner relationship.
Show answer
A lambda is invoked through a nested Runnable and must not return from its caller. Which modifier expresses that restriction?
A reified on the lambda variable B inner C crossinline
Crossinline forbids non-local returns while preserving the parameter's inlining eligibility.
Show answer
A business operation sends a payment and can fail in several ways. What API is usually clearer?
A Hide payment behind an unrelated plus operator B Use get() merely because brackets are short C A named payment method with an explicit result contract
A clear verb and failure contract communicate substantial side effects better than surprising symbolic syntax.
Show answer
A sequence may be infinite. Which expression obtains a bounded sample?
A values.take(5).toList() B values.toList().take(5) C values.count()
take must bound consumption before the terminal operation attempts to materialize the source.
Show answer
Which design best supports changing a customer's display name?
A A mutable display name used directly as the identity key. B A data class key with a mutable equality-relevant id changed after insertion. C An immutable customer-id key with display name stored in the value.
Keep equality-relevant key state stable while editable profile details change independently.
Show answer
A captured digit string must represent an Int from 1 through 100. Which approach handles both limits?
A Use find anywhere in the text and accept the first digits. B Convert with toIntOrNull, then check the resulting value in 1..100. C Check that every character is a digit and assume conversion succeeds.
Numeric representability and the business range are separate from the text's digit shape.
Show answer
Main.kt now declares package shop. Which entry point matches its top-level main?
A stock-demo B shop.Main C shop.MainKt
The package qualifies the generated file-facade class MainKt used by this example.
Show answer
A nullable field should accept omission as null. Which declaration states that ordinary policy?
A val note: String? B val note: String? = null C val note: String
An explicit default handles absence; nullability alone handles a null value, not necessarily a missing key.
Show answer
Which design makes a due-date test independent of the machine's current day?
A Pass a fixed Clock with an explicit business zone. B Call LocalDate.now() inside the assertion with the default zone. C Sleep until midnight before running the test.
A supplied fixed clock makes both the moment and local calendar interpretation deterministic.
Show answer
Where should a necessary bounded suspending cleanup run after cancellation?
A In GlobalScope with no owner. B Around the whole operation forever using NonCancellable. C In finally, using a narrow withContext(NonCancellable) region if needed.
This pattern preserves structured ownership while allowing required cleanup to complete.
Show answer
Which statement accurately describes an in-process Mutex?
A It protects callers that ignore the mutex as strongly as callers that acquire it. B It coordinates cooperating access to local shared state through that mutex. C It automatically locks the same database row in every server process.
External persistence and noncooperating access require their own consistency boundaries.
Show answer
A temporary component shares an expensive source. Which design addresses its lifetime?
A Use an explicit owner scope and an appropriate SharingStarted policy. B Create a detached scope and never retain or cancel it. C Assume replay size automatically closes the source.
The scope owns collection lifetime, while the starting policy controls subscriber-driven behavior.
Show answer
No exercises match those filters.