Inline functions with logic
| Diagnostic | INLINE_FUNCTION_WITH_LOGIC |
| Default severity | Error |
| Gradle property | inlineFunctionWithLogic |
| 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.
@PublishedApiinternal fun decodeValue(payload: String, type: KClass<*>): Any = payloadpublic 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:
analytics-sdkcompiles againstmetrics-sdk1.0 and calls its inline function.- The published
analytics-sdkbinary holds a copy of the 1.0 inline body. - An application depends on the published
analytics-sdkand resolvesmetrics-sdk1.1, which fixes the inline body. analytics-sdkstill runs its copy of the 1.0 body. A newmetrics-sdkversion can't fix it.
Don't
@PublishedApiinternal 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
@PublishedApiinternal fun serviceByType(type: KClass<*>): Any? = TODO()@PublishedApiinternal 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
tryexpressions. 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, andarray[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
@PublishedApiinternal 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
thisreferences. - Literals, including negative numbers and
null. - Object, companion object, and enum entry references.
- Vararg spreads such as
*values.
@PublishedApiinternal fun recordImpl(name: String, value: Long) {}public inline fun Long.recordAs(name: String) {recordImpl(name = name, value = this)}
@PublishedApiinternal 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.
@PublishedApiinternal var limitValue: Int = 0public inline var limit: Intget() = limitValueset(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.
@PublishedApiinternal fun flushImpl() {}public inline val flushAction: () -> Unitget() = ::flushImpl
Class references, type checks, and casts
@PublishedApiinternal 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.
@PublishedApiinternal 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.
@PublishedApiinternal fun beginTrace(name: String): Any = name@PublishedApiinternal 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
apiWatchdog {inlineFunctionWithLogic = WatchdogSeverity.ERROR}
For a direct compiler call:
-P plugin:org.jetbrains.kotlinx.library.api.watchdog:diagnosticSeverity=INLINE_FUNCTION_WITH_LOGIC:error