Skip to main content

Inline functions with logic

DiagnosticINLINE_FUNCTION_WITH_LOGIC
Default severityError
Gradle propertyinlineFunctionWithLogic
Exemption@IntentionallyInlinedLogic

What it reports​

An inline function or property accessor in the public API or declared as @PublishedApi internal whose body isn't a thin wrapper. A thin wrapper has at most one statement after an optional contract { ... } call, and the statement uses only the accepted operations. Parameter defaults must meet the same limits.

@PublishedApi
internal fun decodeValue(payload: String, type: KClass<*>): Any = payload
public inline fun <reified T : Any> decodePayload(payload: String): T {
require(payload.isNotBlank())
return decodeValue(payload, T::class) as T
}

Rationale​

The compiler copies inline bodies into caller binaries. A new library version doesn't replace those copies until callers recompile. Move the logic to a non-inline @PublishedApi internal function and call it from the inline wrapper. Compiled callers then run the implementation of the library version on their runtime classpath.

How the problem appears:

  1. analytics-sdk compiles against metrics-sdk 1.0 and calls its inline function.
  2. The published analytics-sdk binary holds a copy of the 1.0 inline body.
  3. An application depends on the published analytics-sdk and resolves metrics-sdk 1.1, which fixes the inline body.
  4. analytics-sdk still runs its copy of the 1.0 body. A new metrics-sdk version can't fix it.

Don't​

@PublishedApi
internal fun serviceByType(type: KClass<*>): Any? = TODO()
public inline fun <reified T : Any> resolveService(): T {
val service = serviceByType(T::class)
return checkNotNull(service) as T
}

Do​

@PublishedApi
internal fun serviceByType(type: KClass<*>): Any? = TODO()
@PublishedApi
internal fun <T : Any> resolveServiceImpl(type: KClass<T>): T {
val service = serviceByType(type)
return checkNotNull(service) as T
}
public inline fun <reified T : Any> resolveService(): T =
resolveServiceImpl(T::class)

Notes​

A thin wrapper has one of these body forms:

  • An expression body.
  • A block with one statement, with or without return.
  • An empty body.

Accepted operations can nest. Each receiver and argument must be an accepted operation too.

The check rejects these operations because they copy library behavior into caller binaries:

  • Branches, loops, and try expressions.
  • throw, string templates, local declarations, and object expressions.
  • Null-safe calls, Elvis expressions, and !!.
  • Equality expressions such as a == b, for every type.
  • Operator and infix members of built-in types such as Int, Boolean, String, and arrays, in any syntax: x + 1, x.plus(1), !flag, and array[0].
  • Calls, property accesses, and callable references to inline declarations outside the standard library. The compiler copies their bodies through the wrapper.

The check accepts standard library functions and properties, inline or not, such as println(message), text.toInt(), and value.let { it }. Built-in operators and infix members stay rejected.

Accepted operations​

Calls to non-inline functions and constructors​

@PublishedApi
internal fun recordImpl(name: String, value: Long) {}
public inline fun record(name: String, value: Long) {
recordImpl(name, value)
}
public inline fun labelBuilder(prefix: String): StringBuilder {
return StringBuilder(prefix)
}

Values and arguments​

A wrapper can use these values:

  • Parameter reads and this references.
  • Literals, including negative numbers and null.
  • Object, companion object, and enum entry references.
  • Vararg spreads such as *values.
@PublishedApi
internal fun recordImpl(name: String, value: Long) {}
public inline fun Long.recordAs(name: String) {
recordImpl(name = name, value = this)
}
@PublishedApi
internal fun recordAllImpl(vararg values: Long) {}
public inline fun recordAll(vararg values: Long) {
recordAllImpl(*values)
}

Property access through non-inline accessors​

Outside the standard library, a property read must use a non-inline getter and a property assignment must use a non-inline setter.

@PublishedApi
internal var limitValue: Int = 0
public inline var limit: Int
get() = limitValue
set(value) {
limitValue = value
}

Callable references​

Outside the standard library, a callable reference must target a non-inline function or a property with a non-inline getter.

@PublishedApi
internal fun flushImpl() {}
public inline val flushAction: () -> Unit
get() = ::flushImpl

Class references, type checks, and casts​

@PublishedApi
internal fun decodeImpl(payload: String, type: KClass<*>): Any = TODO()
public inline fun <reified T : Any> decode(payload: String): T =
decodeImpl(payload, T::class) as T
public inline fun <reified T : Any> holds(value: Any?): Boolean = value is T

Calls to the wrapper's own function parameter​

The caller writes the lambda body, so it is caller logic. The compiler copies it into the caller binary in any case.

@OptIn(ExperimentalContracts::class)
public inline fun <R> once(block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return block()
}

See Lambda parameters and suspend callers for more details.

Lambda literals with a thin body​

The compiler copies a lambda body into caller binaries too. So each lambda or anonymous function body, nested or not, must meet the same limits as the wrapper.

@PublishedApi
internal fun scheduleFlushImpl(action: () -> Unit) {}
public inline fun afterFlush(crossinline action: () -> Unit) {
scheduleFlushImpl { action() }
}

This lambda has two statements, so the check reports addCallback:

public inline fun addCallback(
key: String,
crossinline callback: Context.() -> Unit,
) {
addCallbackImpl(key) {
println("Running callback: $key")
withApplicationContext { callback() }
}
}

Move the whole lambda body into one non-inline function, so the lambda has one plain call.

User-defined operators and infix functions​

Outside the standard library, the operator or infix function must be non-inline.

public class Vector {
public operator fun plus(other: Vector): Vector = this
}
public inline fun sum(a: Vector, b: Vector): Vector = a + b

Lambda parameters and suspend callers​

An in-place lambda runs in the caller's context. So a suspend caller can call suspend functions in it even though the lambda type isn't suspend. This is what makes inline useful for builder APIs:

public class Parameters(
public val values: Map<String, List<String>>,
)
public class ParametersBuilder {
private var map = mutableMapOf<String, MutableList<String>>()
public fun append(name: String, value: String) {
map.computeIfAbsent(name) { mutableListOf() }.add(value)
}
public fun build(): Parameters {
return Parameters(map.mapValues { it.value.toList() }.toMap())
}
}
public inline fun buildParameters(
builder: ParametersBuilder.() -> Unit,
): Parameters = ParametersBuilder().apply(builder).build()

A suspend caller:

private suspend fun fetchToken(): String = "token"
private suspend fun authorizedQuery(): Parameters = buildParameters {
append("token", fetchToken())
}

Exemption​

If this is intended, apply @IntentionallyInlinedLogic to the declaration.

Use the exemption when the declaration is part of the API design or must stay for backwards compatibility.

@PublishedApi
internal fun beginTrace(name: String): Any = name
@PublishedApi
internal fun endTrace(token: Any) {}
@IntentionallyInlinedLogic(reason = ExemptionReason.API_DESIGN)
public inline fun <R> traced(name: String, block: () -> R): R {
val token = beginTrace(name)
try {
return block()
} finally {
endTrace(token)
}
}

Configuration​

build.gradle.kts
apiWatchdog {
inlineFunctionWithLogic = WatchdogSeverity.ERROR
}

For a direct compiler call:

-P plugin:org.jetbrains.kotlinx.library.api.watchdog:diagnosticSeverity=INLINE_FUNCTION_WITH_LOGIC:error

See also​