Checking unused return values

suggest change

Most Kotlin values are immutable. String, List, data classes, Duration and BigDecimal never change. Their "modifying" functions return a new value instead. If you call one of them and ignore the result, the call does nothing, and the compiler is happy to let you:

data class Order(val id: Int, val total: Int, val tags: List<String>)

fun applyDiscount(order: Order): Order {
    order.copy(total = order.total * 90 / 100)
    return order
}

fun addTag(order: Order, tag: String): Order {
    order.tags + tag
    return order
}

fun cleanName(name: String): String {
    name.trim()
    return name
}

fun main() {
    val order = Order(1, 200, listOf("new"))
    println(applyDiscount(order))
    println(addTag(order, "vip"))
    println("[" + cleanName("  Ann  ") + "]")
}
Order(id=1, total=200, tags=[new])
Order(id=1, total=200, tags=[new])
[  Ann  ]

None of the three functions changes anything. copy(), + on a read-only List and trim() each build a new object, and the code throws it away.

The unused return value checker reports these calls. It was added in Kotlin 2.3 and is still experimental in Kotlin 2.4. You turn it on with the -Xreturn-value-checker compiler flag. It has no @OptIn marker (see Opt-in requirements) and no stable language version enables it. The flag, the annotations and the diagnostics may still change.

All examples were compiled and run with Kotlin 2.4.21 (kotlinc) on JDK 25. See Kotlin compiler versions and experimental features for how -X flags and experimental features work in general.

Turning the checker on

The flag takes one of three values:

Value What it does
disable The default. No checks. The checker annotations are compile errors.
check Reports unused results of functions that are marked as must-use. The standard library is already marked. Your own code is checked only where you add @MustUseReturnValues.
full Like check, but also treats every declaration in the module being compiled as must-use, as if each file had @file:MustUseReturnValues.

Compile the example above with check:

$ kotlinc -Xreturn-value-checker=check bugs.kt -d out
bugs.kt:9:16: warning: unused return value of 'plus'.
    order.tags + tag
               ^
bugs.kt:14:10: warning: unused return value of 'trim'.
    name.trim()
         ^^^^

The standard library's plus and trim are reported. The copy() call is not, because Order is your class and check only knows what the standard library marks. The next section fixes that.

In a Gradle build, pass the flag through freeCompilerArgs:

// build.gradle.kts
plugins {
    kotlin("jvm") version "2.4.21"
}

kotlin {
    compilerOptions {
        freeCompilerArgs.add("-Xreturn-value-checker=check")
    }
}

See Gradle configuration for the rest of the build file.

What the standard library marks

In check mode you get warnings for most standard library functions that return a value, and silence for those that return something you often don't need:

fun main() {
    val nums = listOf(3, 1, 2)
    nums.sorted()                  // warning
    nums.map { it * 2 }            // warning
    nums.isEmpty()                 // warning
    "abc".uppercase()              // warning
    "42".toIntOrNull()             // warning
    runCatching { nums.first() }   // warning

    val list = mutableListOf(1)
    list.add(2)                    // ignorable: returns Boolean
    list.removeAt(0)               // ignorable: returns the removed element
    list + 3                       // warning: `+` copies, it doesn't add
    list += 3                      // fine: this one mutates

    val map = mutableMapOf("a" to 1)
    map.put("b", 2)                // ignorable: returns the old value
    map.remove("a")                // ignorable

    val sb = StringBuilder()
    sb.append("x")                 // ignorable: returns sb for chaining
    nums.forEach { println(it) }   // Unit: never reported
    println(list)
}
$ kotlinc -Xreturn-value-checker=check stdlib.kt -d out
stdlib.kt:3:10: warning: unused return value of 'sorted'.
    nums.sorted()                  // warning
         ^^^^^^
stdlib.kt:4:10: warning: unused return value of 'map'.
    nums.map { it * 2 }            // warning
         ^^^
stdlib.kt:5:10: warning: unused return value of 'isEmpty'.
    nums.isEmpty()                 // warning
         ^^^^^^^
stdlib.kt:6:11: warning: unused return value of 'uppercase'.
    "abc".uppercase()              // warning
          ^^^^^^^^^
stdlib.kt:7:10: warning: unused return value of 'toIntOrNull'.
    "42".toIntOrNull()             // warning
         ^^^^^^^^^^^
stdlib.kt:8:5: warning: unused return value of 'runCatching'.
    runCatching { nums.first() }   // warning
    ^^^^^^^^^^^
stdlib.kt:13:10: warning: unused return value of 'plus'.
    list + 3                       // warning: `+` copies, it doesn't add
         ^

Some things to note:

Marking your own code: @MustUseReturnValues

To check your own functions in check mode, put @MustUseReturnValues on a file or on a class. The annotation is in the kotlin package, so you don't need an import.

On a file

@file:MustUseReturnValues goes at the top of the file, before package. Every function and property declared in the file becomes must-use, including the copy() the compiler generates for a data class:

@file:MustUseReturnValues

data class Order(val id: Int, val total: Int, val tags: List<String>)

fun applyDiscount(order: Order): Order {
    order.copy(total = order.total * 90 / 100)
    return order
}
// addTag, cleanName and main as before
$ kotlinc -Xreturn-value-checker=check bugs2.kt -d out
bugs2.kt:6:11: warning: unused return value of 'copy'.
    order.copy(total = order.total * 90 / 100)
          ^^^^
bugs2.kt:11:16: warning: unused return value of 'plus'.
    order.tags + tag
               ^
bugs2.kt:16:10: warning: unused return value of 'trim'.
    name.trim()
         ^^^^

Now all three bugs are reported. The fix is to return the new value instead of the old one:

@file:MustUseReturnValues

data class Order(val id: Int, val total: Int, val tags: List<String>)

fun applyDiscount(order: Order): Order =
    order.copy(total = order.total * 90 / 100)

fun addTag(order: Order, tag: String): Order =
    order.copy(tags = order.tags + tag)

fun cleanName(name: String): String = name.trim()

fun main() {
    val order = Order(1, 200, listOf("new"))
    println(applyDiscount(order))
    println(addTag(order, "vip"))
    println("[" + cleanName("  Ann  ") + "]")
}
Order(id=1, total=180, tags=[new])
Order(id=1, total=200, tags=[new, vip])
[Ann]

Copying and cloning covers copy() in more detail.

The file annotation covers more than ordinary calls. Constructor calls, property reads and calls to function values all count:

@file:MustUseReturnValues

class Item(val name: String)

fun build(): Item = Item("a")
fun save(item: Item) { println("saved ${item.name}") }
fun maybe(): Item? = null

fun main() {
    Item("x")       // constructor result dropped
    build()
    save(build())   // returns Unit: fine
    maybe()         // nullable results count too
    build().name    // property read dropped
    val lam = { 1 }
    lam()
}
$ kotlinc -Xreturn-value-checker=check items.kt -d out
items.kt:10:5: warning: unused return value of 'Item'.
    Item("x")       // constructor result dropped
    ^^^^
items.kt:11:5: warning: unused return value of 'build'.
    build()
    ^^^^^
items.kt:13:5: warning: unused return value of 'maybe'.
    maybe()         // nullable results count too
    ^^^^^
items.kt:14:13: warning: unused return value of 'name'.
    build().name    // property read dropped
            ^^^^
items.kt:16:5: warning: unused return value of 'invoke'.
    lam()
    ^^^

On a class

@MustUseReturnValues on a class marks its members, including nested classes, inner classes and the companion object. Use it for a value type whose operations all return new instances:

@MustUseReturnValues
class Money(val cents: Long) {
    operator fun plus(other: Money): Money = Money(cents + other.cents)
    fun withTax(rate: Double): Money = Money((cents * (1 + rate)).toLong())
    @IgnorableReturnValue
    fun log(): Money { println("Money($cents)"); return this }
    override fun toString() = "%.2f".format(cents / 100.0)
}

fun helper(): Int = 1

fun main() {
    val price = Money(1000)
    price.withTax(0.2)
    price + Money(50)
    price.log()
    helper()
    println(price)
}
$ kotlinc -Xreturn-value-checker=check c.kt -d out
c.kt:14:11: warning: unused return value of 'withTax'.
    price.withTax(0.2)
          ^^^^^^^
c.kt:15:11: warning: unused return value of 'plus'.
    price + Money(50)
          ^
$ kotlin -cp out CKt
Money(1000)
10.00

helper() is outside the class, so it isn't checked. log() opts out with @IgnorableReturnValue (next section).

The annotation is allowed only on files and classes. You can't put it on a single function:

f.kt:1:1: error: this annotation is not applicable to target 'top level function'. Applicable targets: file, class
@MustUseReturnValues
^^^^^^^^^^^^^^^^^^^^

To mark one function, put it in a file or class that has the annotation, or compile in full mode.

Exceptions: @IgnorableReturnValue

Some functions return a value that callers usually don't need. A cache put returns the previous value. A logger returns its argument so you can chain it. Mark these @IgnorableReturnValue, and they won't be reported even inside a must-use scope:

@file:MustUseReturnValues

class Cache {
    private val map = HashMap<String, String>()

    @IgnorableReturnValue
    fun put(key: String, value: String): String? = map.put(key, value)

    fun get(key: String): String? = map[key]
}

fun main() {
    val cache = Cache()
    cache.put("lang", "Java")            // fine: put is ignorable
    val old = cache.put("lang", "Kotlin") // you can still use the result
    println("replaced $old")
    cache.get("lang")                     // warning
    println(cache.get("lang"))
}
$ kotlinc -Xreturn-value-checker=check ign.kt -d out
ign.kt:17:11: warning: unused return value of 'get'.
    cache.get("lang")                     // warning
          ^^^
$ kotlin -cp out IgnKt
replaced Java
Kotlin

This is the same rule the standard library uses for MutableList.add and MutableMap.put.

Overrides

Ignorability is part of a function's contract. If an interface says a method's result can be ignored, an override must not make it must-use. Callers that use the interface type would get no warning, while callers that use the concrete type would. The compiler warns about that mismatch:

@file:MustUseReturnValues

interface Repo {
    fun insert(name: String): Long
    @IgnorableReturnValue
    fun delete(name: String): Boolean
}

class MemRepo : Repo {
    override fun insert(name: String): Long = 1
    override fun delete(name: String): Boolean = true
}
$ kotlinc -Xreturn-value-checker=check repo.kt -d out
repo.kt:11:18: warning: method 'delete' is located in a scope marked as '@MustUseReturnValues', but marked as '@IgnorableReturnValue' in parent type 'Repo' or its supertypes. Overriding ignorable methods with must-use methods is a semantically incorrect change. Consider marking 'delete' as '@IgnorableReturnValue'.
    override fun delete(name: String): Boolean = true
                 ^^^^^^

Add @IgnorableReturnValue to the override as well.

Discarding a result on purpose

Sometimes you really do want to call a must-use function and drop the result, for example to warm up a cache or to insert a row whose ID you don't need. Assign it to _:

@file:MustUseReturnValues

class Store {
    private val items = mutableListOf<String>()
    fun insert(name: String): Int {
        items += name
        return items.size - 1
    }
    fun dump() = println(items)
}

fun warmUp(): Long = System.nanoTime()

fun main() {
    val store = Store()
    val _ = store.insert("apple")
    val _ = store.insert("pear")
    val _ = warmUp()
    store.dump()
}
$ kotlinc -Xreturn-value-checker=check discard.kt -d out
$ kotlin -cp out DiscardKt
[apple, pear]

val _ = ... is an unnamed local variable. You can use it more than once in the same scope, and it tells the reader that dropping the value is intentional. Unnamed local variables are a separate experimental feature. -Xreturn-value-checker turns them on, but without the flag they are an error:

$ kotlinc discard.kt -d out
discard.kt:1:1: error: ignorability-related annotations are experimental and cannot be used with -Xreturn-value-checker in disabled state.
@file:MustUseReturnValues
^^^^^^^^^^^^^^^^^^^^^^^^^
discard.kt:16:9: error: the feature "unnamed local variables" is experimental and should be enabled explicitly. This can be done by supplying the compiler argument '-XXLanguage:+UnnamedLocalVariables', but note that no stability guarantees are provided.
    val _ = store.insert("apple")
        ^
...

To silence a whole function or file instead, use @Suppress("RETURN_VALUE_NOT_USED").

Lambdas, Java and other edge cases

import java.math.BigDecimal

fun main() {
    val words = listOf(" a ", " b ")
    words.forEach { it.trim() }               // lambda result coerced to Unit
    val trimmed = words.map { it.trim() }     // fine: last expression is the result
    println(trimmed)

    BigDecimal.ONE.add(BigDecimal.TEN)        // Java method: not checked
}

@Suppress("RETURN_VALUE_NOT_USED")
fun legacy() {
    "x".trim()                                // suppressed
}
$ kotlinc -Xreturn-value-checker=check edge.kt -d out
edge.kt:5:24: warning: unused return value of 'trim'. It was coerced to 'Unit' due to a functional parameter type.
    words.forEach { it.trim() }               // lambda result coerced to Unit
                       ^^^^
$ kotlin -cp out EdgeKt
[a, b]

check vs full

full treats every declaration in the module as if its file had @file:MustUseReturnValues. You don't need any annotations. Here is the earlier example without the file annotation:

data class Point(val x: Int, val y: Int)

fun parse(s: String): Int = s.trim().toInt()

class Counter {
    var n = 0
    fun inc(): Int { n++; return n }
}

fun main() {
    val p = Point(1, 2)
    p.copy(x = 5)
    parse(" 42 ")
    Counter().inc()
    println(p)
}
$ kotlinc -Xreturn-value-checker=check b.kt -d out
$ kotlinc -Xreturn-value-checker=full b.kt -d out
b.kt:12:7: warning: unused return value of 'copy'.
    p.copy(x = 5)
      ^^^^
b.kt:13:5: warning: unused return value of 'parse'.
    parse(" 42 ")
    ^^^^^
b.kt:14:15: warning: unused return value of 'inc'.
    Counter().inc()
              ^^^

check reports nothing here because nothing in this file is marked. full reports all three calls.

The cost of full is noise from APIs where ignoring the result is normal. Counter.inc() is one example. Fluent builders that return this are another:

class QueryBuilder {
    private val parts = mutableListOf<String>()
    fun where(cond: String): QueryBuilder { parts += cond; return this }
    fun build(): String = "SELECT * FROM t WHERE " + parts.joinToString(" AND ")
}

fun main() {
    val q = QueryBuilder()
    q.where("a = 1")
    q.where("b = 2")
    println(q.build())
}
$ kotlinc -Xreturn-value-checker=full g.kt -d out
g.kt:9:7: warning: unused return value of 'where'.
    q.where("a = 1")
      ^^^^^
g.kt:10:7: warning: unused return value of 'where'.
    q.where("b = 2")
      ^^^^^

Mark where with @IgnorableReturnValue, or chain the calls. A reasonable migration path is to start with check, annotate the files that hold your value types and pure functions, and switch to full once the remaining warnings are few enough to fix or annotate.

Libraries and consumers

When you compile a library in full mode, or with the annotations, the must-use information is stored in the class files. A consumer that compiles with check gets warnings for the library's functions too:

// lib/lib.kt, compiled with -Xreturn-value-checker=full
package lib

fun normalize(s: String): String = s.trim().lowercase()

class Cache {
    private val map = HashMap<String, String>()
    @IgnorableReturnValue
    fun put(k: String, v: String): String? = map.put(k, v)
    fun get(k: String): String? = map[k]
}
// app/app.kt
import lib.*

fun main() {
    normalize("  Hello ")
    val c = Cache()
    c.put("a", "1")
    c.get("a")
    println(c.get("a"))
}
$ kotlinc -Xreturn-value-checker=full lib/lib.kt -d lib.jar
$ kotlinc -Xreturn-value-checker=check -cp lib.jar app/app.kt -d out
app\app.kt:4:5: warning: unused return value of 'normalize'.
    normalize("  Hello ")
    ^^^^^^^^^
app\app.kt:7:7: warning: unused return value of 'get'.
    c.get("a")
      ^^^

A consumer compiled without the flag gets no warnings. A library compiled with only check and no annotations exports nothing, so its consumers see nothing either.

Making it an error

The diagnostic is a warning. To fail the build on it, raise its level with -Xwarning-level, or use -Werror to fail on any warning:

$ kotlinc -Xreturn-value-checker=check -Xwarning-level=RETURN_VALUE_NOT_USED:error -cp lib.jar app/app.kt -d out
app\app.kt:4:5: error: unused return value of 'normalize'.
    normalize("  Hello ")
    ^^^^^^^^^
app\app.kt:7:7: error: unused return value of 'get'.
    c.get("a")
      ^^^

The annotations need the flag

@MustUseReturnValues and @IgnorableReturnValue are compile errors when the checker is disabled. So once you add them, every build of that code, including IDE builds, CI and other modules that compile those sources, must pass -Xreturn-value-checker:

$ kotlinc c.kt -d out
c.kt:1:1: error: ignorability-related annotations are experimental and cannot be used with -Xreturn-value-checker in disabled state.
@MustUseReturnValues
^^^^^^^^^^^^^^^^^^^^
c.kt:5:5: error: ignorability-related annotations are experimental and cannot be used with -Xreturn-value-checker in disabled state.
    @IgnorableReturnValue
    ^^^^^^^^^^^^^^^^^^^^^

If you only want warnings and no source changes, use check without annotations, or full. Either can be removed later without editing any code.

Summary

The coding conventions recommend read-only data. The checker catches the most common way to misuse it: calling a function that returns a new value and then dropping that value.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents