Standard Library
The parts of the Kotlin standard library outside collections: Result and runCatching, precondition helpers, delegated properties, the time API, text and regex, file I/O, contracts, and small utilities. These are the everyday tools interviewers expect you to reach for instead of writing your own.
part ofKotlinoverview, primer and where to startread it →on this pageshowhide
explore
- How Kotlin Does Its Standard Library5 questions
- Result & Error Handling20 questions
- Result<T> & runCatching5 questions
- Folding & Mapping Result5 questions
- Precondition Functions5 questions
- Exceptions & try/catch as Expression5 questions
- Delegated Properties25 questions
- Property Delegation with by5 questions
- by lazy5 questions
- Delegates.observable & vetoable5 questions
- Custom ReadWriteProperty Delegates5 questions
- provideDelegate5 questions
- Time & Duration20 questions
- Duration & Units5 questions
- measureTime & measureTimedValue5 questions
- TimeSource & TimeMark5 questions
- Clock, Instant & kotlinx-datetime5 questions
- Text & Regex16 questions
- String Extension API6 questions
- Regex Matching & Groups5 questions
- StringBuilder & buildString5 questions
- I/O & Files15 questions
- use for Closeable5 questions
- readText, bufferedReader & writeText5 questions
- File Extensions & Walking5 questions
- Contracts15 questions
- The contract{} DSL5 questions
- returns Effects & Smart Casts5 questions
- callsInPlace Effects5 questions
- Misc Helpers21 questions
- takeIf & takeUnless5 questions
- TODO & repeat6 questions
- Bitwise Operations5 questions
- Random5 questions
questions
137 · 8 sectionsWhat does the stdlib `use` function do, and why is it preferred over manually calling `close()` on a resource?
basics
~10 suse runs your code with a resource like a file, then automatically closes it afterward, even if an error happens. It saves you from forgetting to close it yourself.
How does `by lazy` work as a delegated property, and what does the `LazyThreadSafetyMode` argument control?
basics
~10 sby lazy computes a value the first time you read the property, then caches it for later reads. The mode setting controls whether that first computation is safe when many threads read at once.
Explain `Result<T>` in the Kotlin stdlib: how it represents success/failure, how to create and consume it, and its key limitations.
basics
~10 sResult<T> holds either a successful value or a thrown error, without using exceptions to control flow. You can check which one it is and transform the value safely.
Why are stdlib helpers like the scope functions (`let`, `run`, `apply`, `also`, `with`) and `repeat` declared `inline`, and what does that buy you?
basics
~20 sThese helpers are marked inline, so the compiler copies their code straight into the call site. That avoids creating an extra function object for the lambda, making them as cheap as writing the code by hand.
What do `Delegates.observable` and `Delegates.vetoable` provide, and how do they differ?
basics
~10 sBoth let you run code whenever a property changes. observable notifies you after a change happened; vetoable lets you inspect the new value first and reject it so the property keeps its old value.
Does Kotlin have checked exceptions? Do you need to declare or catch the exceptions a function might throw?
basics
~10 sNo. In Kotlin every exception is unchecked. You are never forced to catch an exception or list it in the function signature. There is no 'throws' clause like in Java.
What is the difference between require(...) and check(...) in the Kotlin standard library, and which exception does each throw?
basics
~10 sBoth check a condition and throw if it is false. require is for bad arguments and throws IllegalArgumentException. check is for a bad object state and throws IllegalStateException.
What is Kotlin's Result<T> type and what does runCatching { } do?
basics
~10 sResult<T> is a box that holds either a successful value or a failure with an exception. runCatching runs a block of code and returns success if it finishes, or failure if it throws.
Given a Kotlin Result<T>, what are the differences between getOrNull(), getOrDefault(), getOrElse(), and getOrThrow() for extracting the value?
basics
~10 sAll four pull the success value out of a Result. getOrNull returns null on failure, getOrDefault returns a fallback you pass, getOrElse computes a fallback from the exception, and getOrThrow re-throws the failure's exception.
Which runtime exception types does the Kotlin stdlib throw for common operations, and when is each raised?
basics
~20 sThe stdlib throws specific runtime exceptions: bad numeric text gives NumberFormatException, a null in a non-null spot gives NullPointerException, a bad index gives IndexOutOfBoundsException, an empty collection's first() gives NoSuchElementException, and a wrong cast gives ClassCastException.
What is the exact operator function signature a class must provide so an instance of it can be used as a custom delegate for a read-only `val` property via `by`?
basics
~10 sThe delegate needs an operator function named getValue that takes the owner object and the property as parameters and returns the value. For a var you also add a setValue.
What does the `by` keyword do in a property declaration like `val name by delegate`, and how is reading that property different from a normal property?
basics
~10 sby hands control of a property over to another object. Instead of storing the value itself, reading or writing the property calls functions on that other object, which decides what to return or do.
What does `val x by lazy { ... }` do in Kotlin, and when does the lambda run?
basics
~10 sIt delays creating a value until the first time you read the property. The block runs once, the result is remembered, and every later read returns that same stored value.
What does Delegates.observable do, and how do you use it to run code every time a property changes?
basics
~20 sDelegates.observable lets a property call a small function every time you assign it a new value. You give it a starting value and a callback that runs after each change, so you can react to updates.
What are the exact required signatures of getValue and setValue for a `var` property delegate, and what is the role of each parameter?
basics
~10 sgetValue takes the owner object and a property-info object and returns the value. setValue takes the owner, the property info, and the new value, and returns nothing. Both must be marked operator.
How do you get the current wall-clock instant in Kotlin's standard library, and what type does it return?
basics
~10 sUse kotlin.time.Clock.System.now(). It returns an Instant, which is a single point in time (a timestamp) — not a date or a clock you read on a wall.
How do you create a kotlin.time.Duration value in Kotlin, and what is the idiomatic way to express '5 seconds' or '100 milliseconds'?
basics
~10 sUse the extension properties on numbers from kotlin.time, like 5.seconds or 100.milliseconds. They return a Duration object that represents a length of time, which you can add, compare, or convert.
What does Kotlin's measureTime { } do, and how is it different from measureTimedValue { }?
basics
~10 smeasureTime runs a block and gives back how long it took as a Duration. measureTimedValue runs a block and gives back both the block's result and how long it took, packaged together.
How do you measure how long a block of code takes using TimeSource.Monotonic, and why use it instead of System.currentTimeMillis()?
basics
~10 sCall TimeSource.Monotonic.markNow() before the code to get a TimeMark, then call mark.elapsedNow() after to get a Duration. It uses a steady clock that never jumps backward, unlike wall-clock millis.
You have an Instant. How do you convert it to a human-readable date and time, and why is a TimeZone required?
basics
~10 sCall instant.toLocalDateTime(timeZone) from kotlinx-datetime. You must pass a time zone because the same instant shows a different clock time in different places (e.g. noon UTC is a different local hour in Tokyo).
How do you create a Regex in Kotlin and check whether a string contains a match versus matches the whole input? Contrast matchEntire, find, and containsMatchIn.
basics
~10 sMake a Regex with Regex("...") or "...".toRegex(). Use containsMatchIn to see if a match appears anywhere, find to get the first match, and matchEntire when the whole string must match the pattern.
Why is building a long string by concatenating with += inside a loop inefficient, and what does StringBuilder do differently?
basics
~10 sKotlin Strings are immutable, so each += makes a brand-new String and copies everything. In a loop that repeats over and over. StringBuilder keeps one growing buffer and just appends, avoiding all those copies.
What is the difference between String.toInt() and String.toIntOrNull(), and when should you use each?
basics
~10 stoInt() converts text to a number but crashes with an error if the text is not a valid number. toIntOrNull() returns null instead of crashing, so you can handle bad input safely.
Using findAll and MatchResult, how do you extract all matches and their captured groups? Explain what groupValues contains and the index convention.
basics
~10 sfindAll returns a lazy sequence of all matches. Each MatchResult has groupValues, a list where index 0 is the whole match and index 1+ are the captured groups in order.
Explain isBlank/isEmpty, ifBlank/ifEmpty, and padStart/padEnd. How do they differ and how do they compose for input normalization?
basics
~10 sisEmpty checks for zero length; isBlank also treats whitespace-only as empty. ifBlank/ifEmpty give a fallback value when the string is blank/empty. padStart/padEnd add filler characters to reach a target width.
Given a java.io.File in Kotlin, how do you get the file's extension and its name without the extension? Name the kotlin.io extension properties and explain what they return for tricky names like "archive.tar.gz" and a dotfile like ".gitignore".
basics
~10 sUse the file's extension property to get the part after the last dot, and nameWithoutExtension to get the name with that part removed. They are Kotlin helpers added on top of java.io.File.
How do you read an entire file into a String and write a String to a file in Kotlin using the standard library? Name the relevant File extension functions.
basics
~10 sUse File("path").readText() to get the whole file as one String, and File("path").writeText("content") to replace the file's contents. Both are Kotlin extension functions that open and close the file for you.
What does the Kotlin standard library `use { }` function do, and why use it instead of manually calling `close()`?
basics
~10 suse { } runs your code with a resource (like a file or stream) and automatically closes it afterwards, even if your code throws an error. It saves you from forgetting to close it.
A teammate uses File.readLines() to process a 5 GB log file and the process runs out of memory. How would you fix it with the Kotlin stdlib, and why does that fix work?
basics
~20 sreadLines loads every line into memory at once. Replace it with useLines or forEachLine, which read the file line by line and only keep one line in memory at a time, so a huge file no longer blows up the heap.
What does File.resolve (and resolveSibling) do in kotlin.io, and how does it differ from new File(parent, child) and from string concatenation when building paths? What happens when the child is an absolute path?
basics
~10 sresolve joins a base directory with a child path safely, using the right separator. resolveSibling joins against the parent. If the child is already absolute, resolve just returns the child instead of nesting it.
Why can you assign to a val exactly once inside a `run { }` lambda and have the compiler accept it as definitely initialized afterwards? What language feature makes this work?
basics
~20 sThe standard-library functions like run and let promise the compiler that the lambda you pass runs exactly once. Because of that promise, the compiler knows a val you set inside the lambda gets set once, so it treats it as initialized.
After calling require(x is String) or x?.let { ... } in stdlib, the compiler often lets you treat x as the narrowed type without an extra cast. What language feature makes the standard library functions like require, check, and requireNotNull propagate type information to the caller?
basics
~10 sKotlin contracts. The stdlib functions declare a promise about how they behave, so the compiler knows that if the call returns normally, a condition is true. It then smart-casts the variable for you.
What is the contract { } block in Kotlin, and why would you add one to a function?
basics
~20 sA contract is a small block at the start of a function that tells the compiler extra facts about how the function behaves, so it can do smarter checks like smart casts after you call your own function.
Write a custom inline function that wraps a block and lets callers initialize a `val` from inside its lambda. What is the exact `contract { }` declaration, what opt-in is needed, and what placement rules apply?
basics
~10 sPut a contract as the very first statement of the function and call callsInPlace(block, EXACTLY_ONCE). Mark it with the experimental contracts opt-in. Then callers can set a val inside the lambda.
Explain the four `InvocationKind` values used with `callsInPlace` and what each one permits the compiler to assume about a `val` (and a `var`) assigned inside the lambda.
basics
~20 sThe kind says how often the lambda runs: exactly once, at most once (zero or one), at least once (one or more), or unknown. Only 'exactly once' lets you assign a val and use it afterward as initialized.
How do you perform bitwise operations in Kotlin, and how does this differ syntactically from Java?
basics
~20 sKotlin has no &, |, ^, <<, >> symbols. Instead it uses named infix functions like and, or, xor, shl, shr on Int and Long. So you write a and b instead of a & b.
How do you generate a random integer within a specific range (e.g. 1 to 6 inclusive) using Kotlin's standard library, and which class do you use?
basics
~10 sUse kotlin.random.Random. Call Random.nextInt(1, 7) to get a number from 1 up to but not including 7. The lower bound is included, the upper bound is excluded.
What do takeIf and takeUnless do, and what does each return?
basics
~10 stakeIf returns the value if a condition is true, otherwise null. takeUnless is the opposite: it returns the value if the condition is false, otherwise null.
What does repeat(n) { } do in Kotlin, and what argument does its lambda receive?
basics
~10 srepeat(n) runs the block of code n times. Each run, the block gets the current count, starting at 0, so you know which iteration you're on.
What does the Kotlin standard-library function TODO("...") do, and what happens at runtime if execution reaches it?
basics
~10 sTODO marks code you haven't written yet. If the program runs that line, it crashes by throwing an error, reminding you to finish it.