Unnecessary Apply

ID

kotlin.unnecessary_apply

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Kotlin

Tags

apply, scope_function

Description

Reports x.apply { …​ } calls whose lambda has no statements or does not reference the implicit this receiver. Such an apply adds nothing to the surrounding expression — the receiver could be used directly.

Rationale

apply is intended to configure the receiver in place and then return it. When the lambda body is empty or contains only code that operates on other objects, the scope function changes nothing about the receiver. Readers must follow the indirection to discover that apply is being used as a no-op, which slows review and hides the actual intent of the code.

// Bad — empty apply lambda
val a = Foo().apply { }

// Bad — lambda does not touch `this`
val b = Foo().apply { other.run() }

// Good — uses implicit this
val c = Foo().apply { name = "x" }

// Good — explicit this access
val d = Foo().apply { this.toString() }

Remediation

Remove the apply call entirely and use the receiver directly. Reserve apply for the cases where the lambda actually configures the receiver via this.