Kotlin Quiz: Test Your Kotlin Knowledge
Pick how many questions you want, choose a difficulty and go. You'll see why each answer is right or wrong, then you can retry to beat your score.
Where does every Kotlin program start?
- In a class called Program
- On the first line of the file
- In a function called start
- In the main function
Which company created Kotlin?
- JetBrains
- Oracle
- Microsoft
Are semicolons required at the end of Kotlin lines?
- No, they're optional
- Yes, always
- Only inside main
- Only after println
What does
//start?- A division
- A string
- A one-line comment
- A new function
What's the difference between print and println?
- println is faster
- print only works with numbers
- println moves to a new line after printing; print doesn't
- There's none
What's the difference between val and var?
- val is for numbers, var for text
- val can't be reassigned; var can
- var is faster
- There's none
What does
9.99.toInt()return?- 10
- 9.99
- An error
- 9
Which type holds a single character?
- Char
- String
- Byte
- Letter
Which name follows Kotlin's naming convention for variables?
- TotalPrice
- totalPrice
- total_price
- TOTALPRICE
Why doesn't Kotlin silently convert an Int to a Double?
- Explicit conversions prevent hidden mistakes and loss of precision
- Doubles aren't supported
- It's a bug
- Ints are always bigger
What is
2 + 3 * 4in Kotlin?- 20
- 14
- 24
- 9
What does
==compare for two strings in Kotlin?- Their memory addresses
- Their lengths only
- Nothing, it's an error
- Their text values
What does
(1..6).random()return?- Always 1
- A random Int from 1 to 6, inclusive
- A random Double
- A list of six numbers
Which type should you use for a value like 5,000,000,000?
- Int
- Char
- Boolean
- Long
What does
true || println("hi") == Unitevaluate, and is "hi" printed?- true, and hi is not printed
- false, and hi is printed
- true, and hi is printed
- An error
What is the index of the first character in a string?
- 1
- 0
- -1
- It depends on the string
What does
" hi ".trim()return?- " hi"
- "hi "
- " hi "
- "hi"
What does
"ABC".lowercase()do to the original string?- Changes it to "abc"
- Nothing; it returns a new string "abc"
- Deletes it
- Throws an error
What is a raw string?
- A triple-quoted string that can span lines and doesn't process escapes like \n
- A string without a type
- An encrypted string
- A string of numbers only
How do you compare two strings while ignoring case?
- a == b
- a.compare(b)
- a.equals(b, ignoreCase = true)
- a === b
Can a variable of type
Stringhold null in Kotlin?- Yes
- Only inside main
- No, only String? can
- Only if it's a var
What type is
nickname?.lengthif nickname is a String??- Int?
- Int
- String
- Boolean
What is a smart cast?
- Converting a String to an Int
- A cast that never fails
- Casting with !!
- Kotlin treating a value as non-null after you've checked it isn't null
What does
"abc".toIntOrNull()return?- 0
- null
- An exception
- "abc"
What does
a ?: b ?: creturn when a is null, b is null and c is 3?- null
- An error
- 3
- b
Does Kotlin have a
? :ternary operator?- Yes
- Only for numbers
- No, because if is an expression
- Only in when
Do when branches fall through to the next branch?
- Yes, unless you add break
- Only for strings
- Only without else
- No, only the matching branch runs
What does
is String ->check in a when branch?- Whether the value's type is String
- Whether the value equals "String"
- Whether the value is empty
- Whether it's a variable
When must a when expression have an else branch?
- When it returns a value and the compiler can't prove every case is covered
- Always
- Never
- Only with ranges
What does
val y = when (2) { 1 -> "one"; 2, 3 -> "two or three"; else -> "other" }give?- "one"
- "two or three"
- "other"
- An error
Does the range
1..3include 3?- No
- Yes
- Only in while loops
- Only with step
What does
repeat(4) { }do?- Runs the block four times, with it from 0 to 3
- Repeats the program four times
- Creates a list of four items
- Waits four seconds
What does
continuedo inside a loop?- Skips the rest of this pass and starts the next one
- Ends the loop
- Restarts from the first item
- Pauses the program
How do you leave an outer loop from inside an inner loop?
- break twice
- Label the outer loop, such as outer@, and use break@outer
- return@inner
- It isn't possible
What does
for (i in 5..1)do?- Counts down from 5 to 1
- Throws an exception
- Nothing: the range is empty
- Counts up from 1 to 5
Which keyword declares a function in Kotlin?
- function
- fun
- def
- void
What does a single-expression function use instead of braces and return?
- =>
- =
- :
- ->
Why use named arguments?
- They run faster
- They're required for every call
- They make parameters mutable
- They make calls clearer and let you skip parameters that have defaults
What does
varargallow?- Passing any number of arguments of that type
- Variable return types
- Changing parameters inside the function
- Calling a function with no name
Can you reassign a parameter inside a Kotlin function, like
n = n + 1?- Yes
- Only for Int parameters
- No, parameters are read-only like val
- Only with default values
Which function creates a read-only list?
- mutableListOf
- arrayListOf
- listOf
- newList
What does
listOf(1, 2, 3).getOrNull(7)return?- 0
- 3
- An exception
- null
How do you check whether "milk" is in a list?
- "milk" in list
- list.has("milk")
- list.find("milk") == true
- list["milk"]
What does
listOf(1, 2, 3, 4).take(2)return?- [3, 4]
- [1, 2]
- 2
- [2]
When might you choose an array instead of a list?
- For most everyday code
- When you need to add items often
- When printing items
- For fixed-size, performance-critical data or when a Java API needs an array
What does
"tea" to 2.5create?- A list
- A string
- A set
- A Pair, used as a map entry
What happens when you add a duplicate to a set?
- Nothing: the set keeps one copy
- An exception
- It's added twice
- The old value is removed
Which gives a value for a key, or 0 if it's missing?
- map[key]!!
- map.getOrDefault(key, 0)
- map.get(key, 0)
- map.find(key)
How do you loop over a map's keys and values?
- for (entry in map.keys)
- map.loop { }
- for ((key, value) in map)
- for (i in 0 until map.size)
Why is
x in setfaster thanx in listfor large collections?- Sets are smaller
- Sets use hashing to jump to the item, while lists check items one by one
- Lists are sorted
- It isn't faster
Do map and filter change the original list?
- Yes
- Only mutable lists
- Only map does
- No, they return new lists
What does
find { }return when nothing matches?- null
- An empty list
- An exception
- The first item
What does
listOf("a", "b", "a").groupingBy { it }.eachCount()return?- [a, b]
- 3
- {2=a, 1=b}
- {a=2, b=1}
What does
sumOf { it.price }do?- Adds up the price of every item
- Sorts by price
- Finds the highest price
- Counts items with a price
When is
asSequence()useful?- For tiny lists
- To make a list mutable
- For very large collections or long chains, so items are processed one at a time without building intermediate lists
- To sort faster
What is a lambda?
- A loop
- A type of list
- A class
- A function without a name, written as a value in braces
What is a higher-order function?
- A very fast function
- A function inside a class
- A function with many parameters
- A function that takes or returns another function
What does
list.filter(::isValid)pass to filter?- The result of isValid
- A new copy of isValid
- A reference to the isValid function
- Nothing
When can a lambda be written outside the brackets?
- When it's the last parameter of the function being called
- Always
- Only for forEach
- Never
What is a closure?
- A lambda that closes a file
- A lambda that captures and remembers variables from where it was created
- A function with no return value
- A finished coroutine
How do you create an object of class Player?
- Player()
- new Player()
- Player.create()
- create Player()
What is
fieldinside a custom setter?- The class name
- A new variable
- The property's stored value
- The parameter
What is the default visibility of a Kotlin class member?
- private
- public
- internal
- protected
What does
require(x > 0) { "msg" }do when x is -1?- Returns false
- Prints the message
- Sets x to 0
- Throws an IllegalArgumentException with the message
What's the risk of
lateinit var?- It makes the class slower
- Reading it before it's assigned throws an exception
- It can only hold Int values
- It's always null
What does
copy()do on a data class?- Creates a new object, optionally with some properties changed
- Copies it to the clipboard
- Changes the original object
- Deletes the object
How does
==compare two data class objects?- By memory address
- By their names
- It always returns false
- By the values of their constructor properties
How does destructuring decide which value goes where?
- By property name
- By property position in the constructor
- Alphabetically
- Randomly
How many items does
setOf(Point(1, 1), Point(1, 1))contain, with Point a data class?- 2
- 0
- An error
- 1
What's the minimum requirement for a data class constructor?
- At least one val or var parameter
- No parameters
- Exactly two parameters
- All parameters must be var
Which keyword replaces a parent's method?
- replace
- super
- override
- open
Can an interface have a function with a body?
- Yes, as a default implementation
- No
- Only if it's private
- Only in abstract classes
What is polymorphism?
- Having many constructors
- Copying objects
- Using many interfaces at once
- One piece of code working with objects of different classes through a shared type, each behaving its own way
What does
super.monthEnd()call?- The subclass's own version
- The parent class's version of the method
- A static function
- Nothing
Why is
class Card : Paymentwritten without brackets after Payment?- Brackets are optional everywhere
- Card has no properties
- Payment is an interface, which has no constructor to call
- It's a data class
What is a singleton?
- A class with exactly one instance
- A class with one property
- A function with one parameter
- A list with one item
Does Kotlin have a static keyword?
- Yes
- Only for functions
- No; companion objects and top-level declarations replace it
- Only in interfaces
When is an object declaration's instance created?
- When the program starts
- The first time it's accessed
- Every time it's used
- Never
What does
object : Greeter { ... }create?- A new interface
- A singleton named Greeter
- An anonymous object that implements Greeter
- A companion object
Why is shared mutable state in singletons risky?
- It uses more memory
- Objects can't hold var properties
- It's slower
- Any code can change it, making bugs hard to trace and tests interfere with each other
What does
Size.valueOf("HUGE")do if HUGE isn't a constant?- Returns null
- Returns the first constant
- Throws an IllegalArgumentException
- Creates HUGE
What does
Size.entriesreturn?- A list of every constant in declaration order
- The number of constants
- The names as Strings
- A map
Which is best for a case with no data in a sealed hierarchy?
- data class Loading()
- enum Loading
- val Loading
- data object Loading
Can enum constants have properties?
- No
- Only String properties
- Yes, through the enum's constructor
- Only in sealed classes
What happens when you add a new case to a sealed interface?
- Nothing
- Every exhaustive when without else stops compiling until the new case is handled
- Existing objects are deleted
- The new case is ignored
What does
finallydo?- Always runs after try and any catch
- Runs only when there's no exception
- Runs only when there is an exception
- Ends the program
What does
check(isConnected) { "Not connected" }do when isConnected is false?- Returns false
- Throws IllegalStateException with the message
- Prints the message
- Connects automatically
What does
runCatching { }return?- The value or null
- A Boolean
- It throws if the block fails
- A Result that holds either the value or the exception
How do you create a custom exception?
- exception MyError
- object MyError : Error
- class MyError(msg: String) : Exception(msg)
- fun MyError() = throw
Why put specific catch blocks before general ones?
- Catch blocks are checked in order, so a general Exception first would catch everything and the specific block would never run
- For speed
- The compiler requires alphabetical order
- So finally runs first
What is the receiver in
fun String.isEmail()?- isEmail
- The return value
- The parameter list
- String: the type the function is called on
Why can't an extension property have an initial value?
- It's a bug
- Extensions can't add stored data to a class, so properties must use a getter
- Properties must be var
- Only Int properties are allowed
What does
infixallow?- Calling a function from Java
- Making a function private
- Calling a one-parameter function without a dot or brackets, like a to b
- Overloading operators
Can you call an extension on String? when the value is null?
- Yes; the extension decides how to handle null
- No, it always crashes
- Only with !!
- Only in main
How is the extension to call chosen?
- By the actual object at run time
- Alphabetically
- Randomly
- By the variable's declared type at compile time
What problem do generics solve?
- Writing code that works with many types while keeping type safety
- Slow loops
- Null errors
- Formatting text
What does
List<*>mean?- A list of anything that can be changed
- A list of some unknown type, read as Any?
- An empty list
- A list of lists
What does
outon a type parameter mean?- The type is private
- The type is optional
- It must be a subclass
- Values of that type are only produced (returned), never consumed
Why can't you write
x is List<String>?- Strings can't be in lists
- is only works with classes
- It's allowed
- Generic type arguments are erased at run time
What does
reifiedrequire?- A data class
- A sealed class
- An inline function
- A var parameter
Which scope functions use
itto refer to the object?- apply and run
- let and also
- with and run
- All of them
What does
letreturn?- The original object
- Unit
- The result of the block
- A Boolean
How is
withdifferent fromrun?- with returns the object
- with takes the object as an argument instead of being called on it
- with uses it
- There's no difference at all
What does
takeIf { it > 0 }return when the value is -3?- null
- -3
- 0
- false
When is a plain local variable better than a scope function?
- Never
- When the scope function makes it unclear what it or this refers to, such as in nested blocks
- Always
- Only in main
What does
delay(1000)do inside a coroutine?- Blocks the thread for a second
- Suspends the coroutine for a second without blocking the thread
- Cancels the coroutine
- Nothing
What is structured concurrency?
- Running coroutines in alphabetical order
- Using only one coroutine
- Scopes wait for their child coroutines and cancel them if one fails, so none are leaked
- A type of dispatcher
What does
withTimeoutOrNull(500) { ... }return if the block takes too long?- An exception
- The partial result
- null
- 500
What does
withContext(Dispatchers.IO) { }do?- Starts a new program
- Runs the block on the IO dispatcher and returns its result
- Cancels the coroutine
- Creates a new scope that never ends
Why is runBlocking rarely used inside Android apps?
- It blocks the current thread, which would freeze the UI on the main thread
- It's deprecated
- It can't call suspend functions
- It only works on servers
Which function receives the values from a flow?
- emit
- await
- collect
- launch
What does
catch { }in a flow handle?- Exceptions anywhere in the program
- Only exceptions in collect
- Exceptions thrown upstream, before it in the chain
- Timeouts only
What does
flowOn(Dispatchers.IO)do?- Changes where collect runs
- Runs the upstream flow work on the IO dispatcher
- Converts the flow to a list
- Cancels the flow
How do you change the value of a MutableStateFlow called state?
- state.emit = 3
- state.set(3)
- state = 3
- state.value = 3, or state.update { 3 }
What does
combine(a, b) { x, y -> x + y }emit?- A new value whenever either flow emits, using the latest value from each
- Only once, at the end
- Pairs strictly one-to-one
- Nothing until both complete
Which function reads a whole file into one String?
- readLines
- loadText
- getText
- readText
Which exception means a file wasn't found?
- NullPointerException
- NumberFormatException
- FileNotFoundException
- IndexOutOfBoundsException
What does
File("photos/2024").mkdirs()do?- Creates a file
- Creates the folder and any missing parent folders
- Deletes the folder
- Lists the folder
Why avoid absolute paths like C:\Users\sam\data.csv?
- They won't exist on other computers or devices
- Kotlin can't read C drives
- They're slower
- Backslashes aren't allowed
What does
File("notes").walk()do?- Deletes every file
- Moves the folder
- Visits every file and folder inside notes, recursively
- Reads the first file
Where do test files usually live in a Gradle Kotlin project?
- src/main/kotlin
- tests/
- build/
- src/test/kotlin
What does @BeforeTest do?
- Runs before each test, giving it fresh setup
- Runs once before all tests
- Skips the next test
- Runs only when a test fails
Why can Kotlin test names contain spaces?
- They can't
- Only on Windows
- Names written in backticks can contain spaces, so tests read like sentences
- Only with JUnit 4
How do you compare Doubles safely in a test?
- Convert them to Strings
- Pass absoluteTolerance to assertEquals
- Round both to Ints
- Doubles can't be tested
Which command runs all tests in a Gradle project?
- kotlin test
- ./gradlew test
- gradle run
- java -test
What does val protect in a val IntArray variable?
- Every element from any mutation
- Reassignment of the variable binding
- The array from being read
Which operation compares one-dimensional array contents?
- contentEquals()
- Ordinary == as a guaranteed list-style comparison
- size.toString() alone
What is Kotlin's default visibility for an ordinary declaration?
- public
- protected
- package-private
What boundary does internal describe?
- Only the same folder
- The same Kotlin compilation module
- Every application installed on the computer
Which operation parses the text "42" as an optional integer?
- value as Int
- value.toIntOrNull()
- value is Int while it remains a String
Why can a custom-getter property resist a smart cast?
- Kotlin forbids every property check
- Getters always return null
- A later read may not have the value checked earlier
When does a normal lazy initializer run?
- Every time the owner is constructed, before any access
- On the first value access, with a successful result retained
- Only when the program exits
Which delegate is intended to accept or reject a proposed assignment?
- Delegates.vetoable
- Delegates.observable as an automatic validator
- A package import
What does Interface by base generate?
- Interface-member forwarding to the supplied object
- A deep clone of base
- A new network connection automatically
A delegated method reads its own object's property. Which property does it normally see?
- Always the wrapper override
- A random global property
- The delegate's own property implementation
Which construction normally creates a plain nested class?
- Outer.Nested()
- Outer().inner without a class name
- new inner Outer automatically
What does inner add to a nested class?
- Automatic immutable snapshots
- A relationship to an outer object instance
- Database persistence
What boundary does return@forEach exit?
- The current lambda invocation
- Every enclosing function automatically
- The JVM process
Which modifier suits a callback that must be stored as an ordinary function value?
- crossinline alone as a storage mechanism
- noinline
- protected
Which function convention supports a + b?
- operator fun plus(...)
- fun appendSymbol(...)
- private set alone
Which object supplies contains for value in container?
- Always the value on the left
- The container on the right
- A global namespace automatically
What starts traversal of this pipeline: source.asSequence().filter { it > 0 }.toList()?
- asSequence always visits every element immediately.
- toList requests the pipeline's elements.
- filter starts a background thread.
Why can sorted() still need substantial memory on a sequence?
- Sequence guarantees every operation uses exactly one element of memory.
- Sorting only examines the first element.
- Global ordering requires examining and retaining finite input before producing sorted results.
What does first === second ask for ordinary reference objects?
- Whether both references identify the same object.
- Whether their hash codes collide.
- Whether their printable text is identical.
Which hash rule is required?
- A hash code must be a permanent unique customer identifier.
- Equal objects must have equal hash codes.
- Unequal objects must always have different hash codes.
Which API is best for requiring the whole input to fit a pattern?
- containsMatchIn
- findAll
- matchEntire
Why apply Regex.escape to a user-entered literal search term?
- Its punctuation should be treated as text rather than pattern operators.
- It encrypts the term.
- It converts the term into an integer.
What is the safest first step for a Java text result that may be absent?
- Force !! everywhere it is used.
- Capture it as nullable and validate at the boundary.
- Assume property-style syntax guarantees a value.
Does Kotlin's lack of checked-exception enforcement mean a Java file read cannot fail?
- Yes; the compiler removes all Java exceptions.
- Yes, provided the result is assigned to val.
- No; the runtime failure remains possible and needs an appropriate policy.
Which declaration adds a library only for tests?
- testImplementation(...)
- application { mainClass.set(...) }
- repositories { mavenCentral() }
What selects the project's Gradle engine for routine commands?
- The quantity of dependencies.
- The checked-in wrapper configuration and scripts.
- The Kotlin source filename.
Which version normally matches the Kotlin compiler version?
- The encoded customer's quantity.
- Every JSON runtime release number.
- The Kotlin serialization compiler plugin version.
What does successful typed JSON decoding establish?
- The input fits the configured representation and model contract.
- The caller owns every referenced record.
- Every business quantity is automatically valid.
Which type best represents a date-only birthday?
- An arbitrary UTC midnight Instant.
- LocalDate.
- A formatted server timestamp string.
What does converting an Instant with atZone do?
- Changes the original event to a different moment.
- Removes the need for zone rules.
- Gives local fields and an offset for the same moment in the chosen zone.
In supervisorScope, what happens when one async child fails?
- Siblings are not cancelled solely by that child failure, but await still observes the failure.
- The parent can never cancel any child.
- Its failure becomes a successful default automatically.
Why is a broad catch around suspending work potentially dangerous?
- All suspending functions are guaranteed never to throw.
- It may swallow CancellationException and defeat the owner's stop request.
- Catch always disables every finally block.
Why can two concurrent counter++ operations lose an update?
- Every coroutine gets a private automatic copy of the variable.
- Int cannot represent positive values.
- Both can read the same old value before either writes its successor.
What must the stock reservation lock cover?
- The availability check and decrement as one protected operation.
- Only the final print statement.
- Only the variable declaration.
Which policy preserves buffered values by waiting when capacity is full?
- Always discard every new value.
- Buffer's suspending overflow policy.
- CollectLatest cancels every producer permanently.
What does collectLatest do when another value arrives?
- Automatically reverses every external effect of the old action.
- Guarantees every action runs to completion.
- Cancels the previous collector action and starts work for the newer value.
About the Kotlin quiz
This Kotlin quiz covers every lesson in the course, from println and variables to coroutines and testing. Many questions show a few lines of Kotlin and ask what they print, because predicting output is the best way to check that you really understand how the language behaves. Others check vocabulary you'll meet in documentation and error messages, such as "nullable", "lambda", "data class" and "suspend function".
If you're still in the beginner stage, choose Easy and a topic you've just finished, such as strings or null safety. After the intermediate lessons, try Mixed with 10 questions to practise collections, lambdas and classes together. Save Exam mode for the end of the course: it hides the answers until you finish, so it's an honest check of what you remember.
When you miss a question, read the explanation and revisit the lesson linked in your results. Kotlin mistakes often come from small details: the difference between val and var, whether a range includes its last number, or when ?. returns null. Spotting them in a quiz is exactly what makes them easy to avoid in real code.
The question bank holds 161 questions drawn from 43 Kotlin lessons: 44 easy, 92 medium and 25 hard. Every time you start, the quiz picks a fresh random selection that matches your settings, so retaking it is a good way to practise. After each answer, or at the end in exam mode, you'll see why the right answer is right, and every question you miss links back to the lesson that teaches it.
What the Kotlin quiz covers
Beginner
Intermediate
Advanced
Language reference
- 26Kotlin Arrays and Primitive Arrays
- 27Kotlin Packages, Imports and Visibility
- 28Kotlin Type Checks, Safe Casts and Smart Casts
- 29Kotlin Delegated Properties, lazy and lateinit
- 30Kotlin Interface Delegation with by
- 31Kotlin Nested and Inner Classes
- 32Kotlin Inline Functions, noinline and crossinline
- 33Kotlin Operator Overloading
- 34Kotlin Sequences and Lazy Pipelines
- 35Kotlin Equality, hashCode and Map Keys
- 36Kotlin Regex Matching and Parsing