How do I declare nullable variables using `?` in Kotlin?

In Kotlin, you declare a nullable variable by adding ? after the type.

var name: String? = null

This means name can hold either a String value or null.

Examples:

var age: Int? = null
age = 25

val email: String? = "[email protected]"
val phone: String? = null

Without ?, Kotlin does not allow null:

var name: String = null // Error

With ?, you must handle possible null safely:

val name: String? = null

println(name?.length) // Safe call, prints null instead of crashing

You can also provide a default value with the Elvis operator ?::

val name: String? = null
val length = name?.length ?: 0

println(length) // 0

So the basic pattern is:

var variableName: Type? = null

How do I handle null values safely in Kotlin?

Kotlin handles null safety through its type system: a normal type like String cannot be null, while a nullable type like String? can be null.

1. Use nullable types when a value may be null

val name: String = "Alice"   // Cannot be null
val nickname: String? = null // Can be null

If a value is nullable, Kotlin will not let you access it directly without handling the null case.

val length = nickname.length // Compile error

2. Use the safe-call operator ?.

Use ?. to access a property or call a function only when the value is not null.

val name: String? = getName()

val length: Int? = name?.length

If name is null, length becomes null instead of throwing a NullPointerException.

3. Use the Elvis operator ?: for defaults

Use ?: to provide a fallback value when something is null.

val name: String? = getName()

val length: Int = name?.length ?: 0

You can also return early or throw an exception:

fun printName(name: String?) {
    val nonNullName = name ?: return
    println(nonNullName)
}
fun requireName(name: String?) {
    val nonNullName = name ?: error("Name is required")
    println(nonNullName)
}

4. Use if null checks and smart casts

After checking that a nullable value is not null, Kotlin smart-casts it to a non-null type.

fun printLength(text: String?) {
    if (text != null) {
        println(text.length)
    } else {
        println("Text is null")
    }
}

Inside the if block, text is treated as a non-null String.

5. Use let to run code only when non-null

?.let { ... } is useful when you want to execute a block only if the value exists.

val email: String? = getEmail()

email?.let {
    println("Sending email to $it")
}

You can combine it with Elvis for the null case:

email?.let {
    println("Sending email to $it")
} ?: println("No email available")

6. Avoid !! unless you truly mean “crash if null”

The not-null assertion operator !! converts a nullable value to a non-null value, but throws a NullPointerException if the value is null.

val name: String? = getName()
val length = name!!.length

Prefer safer alternatives:

val length = name?.length ?: 0

Use !! only when null would indicate a serious programmer error, and you want the program to fail immediately.

7. Prefer non-nullable function parameters when possible

If a function requires a value, declare it as non-nullable.

fun greet(name: String) {
    println("Hello, $name")
}

If null is a valid input, declare it explicitly:

fun greet(name: String?) {
    println("Hello, ${name ?: "Guest"}")
}

Quick guide

Situation Use
Access nullable value safely value?.property
Provide default if null value ?: default
Run code only if non-null value?.let { ... }
Check manually if (value != null)
Require non-null and crash if null value!!
Disallow null entirely Use non-null type, e.g. String

In general: prefer non-nullable types, use ?. and ?: for safe handling, and avoid !! unless absolutely necessary.

How do I combine Kotlin collections with coroutines and flows for asynchronous processing?

You typically combine Kotlin collections, coroutines, and Flow by using:

  • collections for in-memory data
  • coroutines for concurrency / async work
  • Flow for asynchronous streams of values

Basic idea

If you have a collection:

val ids = listOf(1, 2, 3, 4, 5)

You can turn it into a Flow:

val idFlow = ids.asFlow()

Then process each item asynchronously using Flow operators:

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
    val ids = listOf(1, 2, 3, 4, 5)

    ids.asFlow()
        .map { id ->
            fetchUser(id)
        }
        .collect { user ->
            println(user)
        }
}

suspend fun fetchUser(id: Int): String {
    delay(500)
    return "User $id"
}

Here:

  • asFlow() converts the collection into a Flow
  • map { } applies a suspending transformation
  • collect { } starts the flow and consumes results

Sequential asynchronous processing

By default, Flow processes elements sequentially:

ids.asFlow()
    .map { id ->
        fetchUser(id)
    }
    .collect { user ->
        println(user)
    }

Even though fetchUser is suspending, each item is processed one after another.

Concurrent processing with flatMapMerge

If you want to process multiple items concurrently, use flatMapMerge:

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
    val ids = listOf(1, 2, 3, 4, 5)

    ids.asFlow()
        .flatMapMerge(concurrency = 3) { id ->
            flow {
                emit(fetchUser(id))
            }
        }
        .collect { user ->
            println(user)
        }
}

suspend fun fetchUser(id: Int): String {
    delay(500)
    return "User $id"
}

This allows up to 3 items to be processed at the same time.

Note: flatMapMerge may emit results out of the original order.

Keeping order while doing concurrent work

If you need concurrency but want results in the original order, you can use async with a collection:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val ids = listOf(1, 2, 3, 4, 5)

    val users = ids.map { id ->
        async {
            fetchUser(id)
        }
    }.awaitAll()

    println(users)
}

suspend fun fetchUser(id: Int): String {
    delay(500)
    return "User $id"
}

awaitAll() returns results in the same order as the original list.

Filtering and transforming Flow values

You can use familiar collection-like operators:

ids.asFlow()
    .filter { id ->
        id % 2 == 0
    }
    .map { id ->
        fetchUser(id)
    }
    .collect { user ->
        println(user)
    }

This is similar to collection processing, but it supports suspending operations.

Collecting a Flow back into a collection

If you need a List again:

val users: List<String> = ids.asFlow()
    .map { id -> fetchUser(id) }
    .toList()

Because toList() collects the flow, it must be called from a coroutine or suspend function.

Using flowOn for background work

You can move upstream processing to a dispatcher:

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
    val ids = listOf(1, 2, 3, 4, 5)

    ids.asFlow()
        .map { id ->
            fetchUser(id)
        }
        .flowOn(Dispatchers.IO)
        .collect { user ->
            println(user)
        }
}

This is useful for I/O-bound work such as network or database calls.

Handling errors

Use catch to handle exceptions from upstream operators:

ids.asFlow()
    .map { id ->
        fetchUser(id)
    }
    .catch { error ->
        emit("Fallback user because of: ${error.message}")
    }
    .collect { user ->
        println(user)
    }

Example: process URLs asynchronously

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
    val urls = listOf(
        "https://example.com/a",
        "https://example.com/b",
        "https://example.com/c"
    )

    val results = urls.asFlow()
        .flatMapMerge(concurrency = 2) { url ->
            flow {
                val content = download(url)
                emit(url to content.length)
            }
        }
        .toList()

    println(results)
}

suspend fun download(url: String): String {
    delay(1_000)
    return "Content from $url"
}

When to use what

Need Use
Simple in-memory transformation Collection operators: map, filter
Suspending work per item, sequential asFlow().map { suspendCall() }
Suspending work per item, concurrent flatMapMerge
Concurrent work while preserving order map { async { ... } }.awaitAll()
Continuous stream of values Flow
Convert Flow back to List toList()

In short:

val results = items.asFlow()
    .filter { shouldProcess(it) }
    .flatMapMerge(concurrency = 4) { item ->
        flow {
            emit(processAsync(item))
        }
    }
    .toList()

That pattern is a good starting point for asynchronous collection processing with Kotlin coroutines and flows.

How do I use inline functions and reified types in collection processing?

In Kotlin, inline functions and reified type parameters are especially useful in collection processing when you want to write generic, type-safe utilities that still need access to the actual runtime type.

Normally, generic type information is erased at runtime, but reified type parameters in inline functions let you do checks like is T, as T, or filterIsInstance<T>().

Basic idea

inline fun <reified T> Iterable<*>.onlyOfType(): List<T> {
    return this.filterIsInstance<T>()
}

Usage:

val items: List<Any> = listOf("Kotlin", 42, "Java", 3.14)

val strings = items.onlyOfType<String>()

println(strings) // [Kotlin, Java]

Because T is reified, Kotlin knows at runtime that T is String.

Why inline is required

A reified type parameter is only allowed on an inline function:

inline fun <reified T> someFunction(value: Any): Boolean {
    return value is T
}

This works because the compiler substitutes the function body at the call site and preserves the concrete type.

This would not compile:

fun <T> someFunction(value: Any): Boolean {
    return value is T // Error: cannot check for instance of erased type
}

Filtering a collection by type

inline fun <reified T> List<*>.filterByType(): List<T> {
    return filterIsInstance<T>()
}

Example:

val mixed = listOf(1, "two", 3L, "four", 5.0)

val strings = mixed.filterByType<String>()
val ints = mixed.filterByType<Int>()

println(strings) // [two, four]
println(ints)    // [1]

Mapping only matching elements

You can combine reified type checks with mapNotNull:

inline fun <reified T, R> Iterable<*>.mapIfType(
    transform: (T) -> R
): List<R> {
    return mapNotNull { item ->
        if (item is T) transform(item) else null
    }
}

Usage:

val values: List<Any> = listOf("one", 2, "three", 4)

val lengths = values.mapIfType<String> { it.length }

println(lengths) // [3, 5]

Finding the first item of a type

inline fun <reified T> Iterable<*>.firstOfTypeOrNull(): T? {
    return firstOrNull { it is T } as? T
}

Usage:

val items: List<Any> = listOf(10, "hello", 20)

val firstString = items.firstOfTypeOrNull<String>()

println(firstString) // hello

A slightly cleaner version uses filterIsInstance:

inline fun <reified T> Iterable<*>.firstOfTypeOrNull(): T? {
    return filterIsInstance<T>().firstOrNull()
}

Grouping elements by runtime type

inline fun <reified T> Iterable<*>.partitionByType(): Pair<List<T>, List<Any?>> {
    val matching = mutableListOf<T>()
    val others = mutableListOf<Any?>()

    for (item in this) {
        if (item is T) {
            matching += item
        } else {
            others += item
        }
    }

    return matching to others
}

Usage:

val data = listOf("a", 1, "b", 2.0, null)

val result = data.partitionByType<String>()

println(result.first)  // [a, b]
println(result.second) // [1, 2.0, null]

Processing collections with inline lambdas

inline is also useful for performance when you pass lambdas to collection-like helper functions. It avoids allocating a function object in many cases.

inline fun <T, R> Iterable<T>.transformEach(
    transform: (T) -> R
): List<R> {
    val result = ArrayList<R>()

    for (item in this) {
        result += transform(item)
    }

    return result
}

Usage:

val numbers = listOf(1, 2, 3)

val doubled = numbers.transformEach { it * 2 }

println(doubled) // [2, 4, 6]

Combining inline and reified

A common pattern is a type-safe processing function:

inline fun <reified T, R> Iterable<*>.processType(
    transform: (T) -> R
): List<R> {
    return mapNotNull { item ->
        if (item is T) {
            transform(item)
        } else {
            null
        }
    }
}

Example:

val events: List<Any> = listOf(
    "login",
    404,
    "logout",
    500
)

val uppercasedEvents = events.processType<String> {
    it.uppercase()
}

println(uppercasedEvents) // [LOGIN, LOGOUT]

Example with sealed classes

sealed interface Event

data class ClickEvent(val x: Int, val y: Int) : Event
data class TextEvent(val text: String) : Event
data class ErrorEvent(val message: String) : Event

inline fun <reified T : Event> Iterable<Event>.ofEventType(): List<T> {
    return filterIsInstance<T>()
}

Usage:

val events: List<Event> = listOf(
    ClickEvent(10, 20),
    TextEvent("hello"),
    ErrorEvent("failed"),
    TextEvent("world")
)

val textEvents = events.ofEventType<TextEvent>()

println(textEvents.map { it.text }) // [hello, world]

Important limitations

1. reified only works in inline functions

inline fun <reified T> ok(value: Any) = value is T

But this does not work:

fun <T> notOk(value: Any) = value is T

2. It does not fully solve nested generic type erasure

This can be misleading:

val data: List<Any> = listOf(listOf("a"), listOf(1))

val stringLists = data.filterIsInstance<List<String>>()

Because of type erasure, the runtime can check that each item is a List, but not that each list contains String.

A safer approach:

val stringLists = data
    .filterIsInstance<List<*>>()
    .filter { list -> list.all { it is String } }
    .map { list -> list.map { it as String } }

Practical collection utilities

inline fun <reified T> Iterable<*>.countOfType(): Int {
    return count { it is T }
}

inline fun <reified T> Iterable<*>.containsType(): Boolean {
    return any { it is T }
}

inline fun <reified T> Iterable<*>.withoutType(): List<Any?> {
    return filterNot { it is T }
}

Usage:

val values = listOf("a", 1, "b", 2.0)

println(values.countOfType<String>())   // 2
println(values.containsType<Double>())  // true
println(values.withoutType<String>())   // [1, 2.0]

Rule of thumb

Use inline + reified when:

  • You need to check item is T
  • You need to cast with as T or as? T
  • You want to call APIs like filterIsInstance<T>()
  • You want type-safe helpers for heterogeneous collections
  • You want to avoid passing KClass<T> or Class<T> manually

For ordinary collection transformations where no runtime type check is needed, a regular generic function is usually enough:

fun <T, R> Iterable<T>.mapCustom(transform: (T) -> R): List<R> {
    return map(transform)
}

How do I write domain-specific extensions for collections in Kotlin?

Domain-specific collection extensions in Kotlin are usually extension functions or extension properties on Iterable<T>, List<T>, Set<T>, Map<K, V>, or more specific collection types that encode concepts from your domain.

They let you write expressive code like:

val overdueInvoices = invoices.overdue()
val activeUsers = users.active()
val totalRevenue = orders.totalRevenue()

instead of repeatedly writing filtering, grouping, or aggregation logic inline.

1. Start with simple extension functions

Suppose you have a domain model:

import java.math.BigDecimal
import java.time.LocalDate

data class Invoice(
    val id: String,
    val customerId: String,
    val amount: BigDecimal,
    val dueDate: LocalDate,
    val paid: Boolean
)

You can add collection extensions for common domain queries:

import java.time.LocalDate

fun Iterable<Invoice>.overdue(today: LocalDate = LocalDate.now()): List<Invoice> =
    filter { invoice ->
        !invoice.paid && invoice.dueDate.isBefore(today)
    }

fun Iterable<Invoice>.paid(): List<Invoice> =
    filter { it.paid }

fun Iterable<Invoice>.unpaid(): List<Invoice> =
    filterNot { it.paid }

Usage:

val overdueInvoices = invoices.overdue()
val unpaidInvoices = invoices.unpaid()

2. Add domain-specific aggregation

Collections often need totals, counts, averages, or summaries.

import java.math.BigDecimal

fun Iterable<Invoice>.totalAmount(): BigDecimal =
    fold(BigDecimal.ZERO) { total, invoice ->
        total + invoice.amount
    }

fun Iterable<Invoice>.totalPaidAmount(): BigDecimal =
    paid().totalAmount()

fun Iterable<Invoice>.totalOutstandingAmount(): BigDecimal =
    unpaid().totalAmount()

Usage:

val outstanding = invoices.totalOutstandingAmount()

This is easier to understand than:

val outstanding = invoices
    .filterNot { it.paid }
    .fold(BigDecimal.ZERO) { total, invoice -> total + invoice.amount }

3. Group collections using domain language

You can wrap common groupBy patterns:

fun Iterable<Invoice>.groupedByCustomer(): Map<String, List<Invoice>> =
    groupBy { it.customerId }

fun Iterable<Invoice>.overdueByCustomer(
    today: LocalDate = LocalDate.now()
): Map<String, List<Invoice>> =
    overdue(today).groupedByCustomer()

Usage:

val invoicesByCustomer = invoices.groupedByCustomer()
val overdueByCustomer = invoices.overdueByCustomer()

4. Prefer Iterable<T> when possible

If your function only needs to iterate, prefer Iterable<T>:

fun Iterable<Invoice>.overdue(): List<Invoice> =
    filter { !it.paid && it.dueDate.isBefore(LocalDate.now()) }

Use List<T> only when list-specific behavior matters, such as ordering by index:

fun List<Invoice>.firstOverdueOrNull(
    today: LocalDate = LocalDate.now()
): Invoice? =
    firstOrNull { !it.paid && it.dueDate.isBefore(today) }

Use Sequence<T> if you want lazy processing for large pipelines:

fun Sequence<Invoice>.overdue(
    today: LocalDate = LocalDate.now()
): Sequence<Invoice> =
    filter { !it.paid && it.dueDate.isBefore(today) }

5. Use extension properties for simple derived facts

If a value does not need parameters, an extension property can read nicely:

val Iterable<Invoice>.totalAmount: BigDecimal
    get() = fold(BigDecimal.ZERO) { total, invoice ->
        total + invoice.amount
    }

val Iterable<Invoice>.hasOverdueInvoices: Boolean
    get() = any { !it.paid && it.dueDate.isBefore(LocalDate.now()) }

Usage:

if (invoices.hasOverdueInvoices) {
    println("Some invoices are overdue")
}

println(invoices.totalAmount)

Use properties for cheap, parameterless concepts. Use functions when the operation accepts arguments or does meaningful work.

6. Create richer domain operations

For example, with an order domain:

import java.math.BigDecimal

data class Order(
    val id: String,
    val customerId: String,
    val status: OrderStatus,
    val total: BigDecimal
)

enum class OrderStatus {
    Draft,
    Submitted,
    Paid,
    Cancelled
}

Extensions:

fun Iterable<Order>.paid(): List<Order> =
    filter { it.status == OrderStatus.Paid }

fun Iterable<Order>.submitted(): List<Order> =
    filter { it.status == OrderStatus.Submitted }

fun Iterable<Order>.cancelled(): List<Order> =
    filter { it.status == OrderStatus.Cancelled }

fun Iterable<Order>.totalRevenue(): BigDecimal =
    paid().fold(BigDecimal.ZERO) { total, order ->
        total + order.total
    }

fun Iterable<Order>.forCustomer(customerId: String): List<Order> =
    filter { it.customerId == customerId }

Usage:

val revenue = orders.totalRevenue()
val customerOrders = orders.forCustomer("customer-123")
val paidCustomerOrders = orders.forCustomer("customer-123").paid()

7. Avoid making extensions too generic

This is usually good:

fun Iterable<Order>.totalRevenue(): BigDecimal =
    paid().fold(BigDecimal.ZERO) { total, order -> total + order.total }

This is probably too vague:

fun Iterable<Order>.goodOnes(): List<Order> =
    filter { it.status == OrderStatus.Paid }

Choose names that reflect your domain clearly: overdue, billable, fulfilled, activeSubscriptions, totalRevenue, groupedByCustomer, etc.

8. Consider nullable and empty collections

Be explicit about what happens for empty collections:

fun Iterable<Invoice>.largestInvoiceOrNull(): Invoice? =
    maxByOrNull { it.amount }

fun Iterable<Invoice>.averageAmountOrZero(): BigDecimal {
    val invoices = toList()

    if (invoices.isEmpty()) {
        return BigDecimal.ZERO
    }

    val total = invoices.totalAmount()
    return total.divide(BigDecimal(invoices.size))
}

Prefer OrNull suffixes when returning nullable results:

fun Iterable<Invoice>.oldestUnpaidInvoiceOrNull(): Invoice? =
    unpaid().minByOrNull { it.dueDate }

9. Use generic extensions when there is a reusable domain interface

If several entities share domain behavior, define an interface:

interface HasCustomer {
    val customerId: String
}

data class Invoice(
    val id: String,
    override val customerId: String,
    val amount: BigDecimal,
    val paid: Boolean
) : HasCustomer

data class Order(
    val id: String,
    override val customerId: String,
    val total: BigDecimal
) : HasCustomer

Then write a generic extension:

fun <T : HasCustomer> Iterable<T>.forCustomer(customerId: String): List<T> =
    filter { it.customerId == customerId }

fun <T : HasCustomer> Iterable<T>.groupedByCustomer(): Map<String, List<T>> =
    groupBy { it.customerId }

Usage:

val customerInvoices = invoices.forCustomer("customer-123")
val customerOrders = orders.forCustomer("customer-123")

10. Keep mutability clear

Prefer returning new collections:

fun Iterable<Order>.withoutCancelled(): List<Order> =
    filter { it.status != OrderStatus.Cancelled }

Be careful with extensions that mutate the receiver:

fun MutableList<Order>.removeCancelled() {
    removeAll { it.status == OrderStatus.Cancelled }
}

If an extension mutates state, make that obvious in the name: removeCancelled, sortByPriorityInPlace, markAllAsPaid, etc.

11. Organize extensions by domain

A common structure is:

src/main/kotlin/
  billing/
    Invoice.kt
    InvoiceCollectionExtensions.kt
  orders/
    Order.kt
    OrderCollectionExtensions.kt

Example:

package billing

fun Iterable<Invoice>.overdue(): List<Invoice> =
    filter { !it.paid }

fun Iterable<Invoice>.totalAmount(): BigDecimal =
    fold(BigDecimal.ZERO) { total, invoice -> total + invoice.amount }

Then import them where needed:

import billing.overdue
import billing.totalAmount

Good rules of thumb

  • Use Iterable<T> for most collection extensions.
  • Use List<T> only when order or index matters.
  • Use Sequence<T> for lazy pipelines.
  • Use extension properties for cheap, parameterless values.
  • Use extension functions for parameterized or non-trivial operations.
  • Prefer clear domain names over technical names.
  • Return new collections unless mutation is intentional.
  • Use OrNull suffixes for nullable lookups.
  • Keep extensions close to the domain they describe.

A typical domain-specific collection extension looks like this:

fun Iterable<Invoice>.overdue(today: LocalDate = LocalDate.now()): List<Invoice> =
    filter { !it.paid && it.dueDate.isBefore(today) }

And its value is that the rest of your application can speak in domain terms:

val amountToCollect = invoices
    .overdue()
    .totalAmount()