Nested Scope Functions

ID

kotlin.nested_scope_functions

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Kotlin

Tags

readability, style

Description

Reports scope function calls (let, run, apply, also, with, use) that are nested beyond a configurable depth threshold.

Each scope function changes the implicit receiver (this) or introduces a new lambda parameter (it), so deeply nested combinations quickly make it unclear which object each name refers to.

Rationale

Two or more levels of nested scope functions are hard to follow because each level changes it/this:

// Bad — three levels of context switching
a?.let {
    b?.run {
        c?.also {  // FLAW — depth 2
            it.value = 1
        }
    }
}

// Good — extract into a named function
fun configureC(c: MyClass) { c.value = 1 }

a?.let {
    b?.run { configureC(c) }
}

Remediation

Extract the inner logic into a named function or refactor the chain using direct references. The maximum depth (default 2) is configurable via the maxDepth property.