skip to content

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 pageshow

explore

questions

137 · 8 sections

What does the stdlib `use` function do, and why is it preferred over manually calling `close()` on a resource?

level: juniorimportance: must knowfreq 70%
basics
~10 s

use 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.

open as a page

How does `by lazy` work as a delegated property, and what does the `LazyThreadSafetyMode` argument control?

level: middleimportance: must knowfreq 65%
basics
~10 s

by 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.

open as a page

Explain `Result<T>` in the Kotlin stdlib: how it represents success/failure, how to create and consume it, and its key limitations.

level: middleimportance: should knowfreq 60%
basics
~10 s

Result<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.

open as a page

Why are stdlib helpers like the scope functions (`let`, `run`, `apply`, `also`, `with`) and `repeat` declared `inline`, and what does that buy you?

level: seniorimportance: should knowfreq 45%
basics
~20 s

These 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.

open as a page

What do `Delegates.observable` and `Delegates.vetoable` provide, and how do they differ?

level: seniorimportance: should knowfreq 40%
basics
~10 s

Both 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.

open as a page

Does Kotlin have checked exceptions? Do you need to declare or catch the exceptions a function might throw?

level: juniorimportance: must knowfreq 78%
basics
~10 s

No. 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.

open as a page

What is the difference between require(...) and check(...) in the Kotlin standard library, and which exception does each throw?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Both 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.

open as a page

What is Kotlin's Result<T> type and what does runCatching { } do?

level: juniorimportance: must knowfreq 60%
basics
~10 s

Result<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.

open as a page

Given a Kotlin Result<T>, what are the differences between getOrNull(), getOrDefault(), getOrElse(), and getOrThrow() for extracting the value?

level: juniorimportance: must knowfreq 70%
basics
~10 s

All 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.

open as a page

Which runtime exception types does the Kotlin stdlib throw for common operations, and when is each raised?

level: middleimportance: must knowfreq 64%
basics
~20 s

The 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.

open as a page

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`?

level: juniorimportance: must knowfreq 55%
basics
~10 s

The 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.

open as a page

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?

level: juniorimportance: must knowfreq 70%
basics
~10 s

by 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.

open as a page

What does `val x by lazy { ... }` do in Kotlin, and when does the lambda run?

level: juniorimportance: must knowfreq 78%
basics
~10 s

It 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.

open as a page

What does Delegates.observable do, and how do you use it to run code every time a property changes?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Delegates.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.

open as a page

What are the exact required signatures of getValue and setValue for a `var` property delegate, and what is the role of each parameter?

level: middleimportance: must knowfreq 60%
basics
~10 s

getValue 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.

open as a page

How do you get the current wall-clock instant in Kotlin's standard library, and what type does it return?

level: juniorimportance: must knowfreq 60%
basics
~10 s

Use 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.

open as a page

How do you create a kotlin.time.Duration value in Kotlin, and what is the idiomatic way to express '5 seconds' or '100 milliseconds'?

level: juniorimportance: must knowfreq 60%
basics
~10 s

Use 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.

open as a page

What does Kotlin's measureTime { } do, and how is it different from measureTimedValue { }?

level: juniorimportance: must knowfreq 55%
basics
~10 s

measureTime 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.

open as a page

How do you measure how long a block of code takes using TimeSource.Monotonic, and why use it instead of System.currentTimeMillis()?

level: juniorimportance: must knowfreq 55%
basics
~10 s

Call 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.

open as a page

You have an Instant. How do you convert it to a human-readable date and time, and why is a TimeZone required?

level: middleimportance: must knowfreq 50%
basics
~10 s

Call 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).

open as a page

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.

level: juniorimportance: must knowfreq 70%
basics
~10 s

Make 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.

open as a page

Why is building a long string by concatenating with += inside a loop inefficient, and what does StringBuilder do differently?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Kotlin 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.

open as a page

What is the difference between String.toInt() and String.toIntOrNull(), and when should you use each?

level: juniorimportance: must knowfreq 75%
basics
~10 s

toInt() 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.

open as a page

Using findAll and MatchResult, how do you extract all matches and their captured groups? Explain what groupValues contains and the index convention.

level: middleimportance: must knowfreq 60%
basics
~10 s

findAll 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.

open as a page

Explain isBlank/isEmpty, ifBlank/ifEmpty, and padStart/padEnd. How do they differ and how do they compose for input normalization?

level: middleimportance: must knowfreq 65%
basics
~10 s

isEmpty 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.

open as a page

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".

level: juniorimportance: must knowfreq 55%
basics
~10 s

Use 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.

open as a page

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.

level: juniorimportance: must knowfreq 75%
basics
~10 s

Use 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.

open as a page

What does the Kotlin standard library `use { }` function do, and why use it instead of manually calling `close()`?

level: juniorimportance: must knowfreq 70%
basics
~10 s

use { } 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.

open as a page

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?

level: middleimportance: must knowfreq 65%
basics
~20 s

readLines 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.

open as a page

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?

level: middleimportance: should knowfreq 45%
basics
~10 s

resolve 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.

open as a page

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?

level: juniorimportance: must knowfreq 55%
basics
~20 s

The 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.

open as a page

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?

level: juniorimportance: must knowfreq 55%
basics
~10 s

Kotlin 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.

open as a page

What is the contract { } block in Kotlin, and why would you add one to a function?

level: juniorimportance: should knowfreq 35%
basics
~20 s

A 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.

open as a page

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?

level: middleimportance: should knowfreq 35%
basics
~10 s

Put 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.

open as a page

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.

level: middleimportance: should knowfreq 45%
basics
~20 s

The 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.

open as a page

How do you perform bitwise operations in Kotlin, and how does this differ syntactically from Java?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Kotlin 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.

open as a page

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?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Use 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.

open as a page

What do takeIf and takeUnless do, and what does each return?

level: juniorimportance: must knowfreq 55%
basics
~10 s

takeIf 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.

open as a page

What does repeat(n) { } do in Kotlin, and what argument does its lambda receive?

level: juniorimportance: must knowfreq 55%
basics
~10 s

repeat(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.

open as a page

What does the Kotlin standard-library function TODO("...") do, and what happens at runtime if execution reaches it?

level: juniorimportance: must knowfreq 60%
basics
~10 s

TODO marks code you haven't written yet. If the program runs that line, it crashes by throwing an error, reminding you to finish it.

open as a page