Delegate To Var

ID

kotlin.delegate_to_var

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Kotlin

Tags

reliability

Description

Reports a class delegation class X(…​) : I by target whose target is a var property of the enclosing class. Kotlin evaluates the delegate expression once, at construction time, and stores the resulting reference in a hidden synthetic field. Reassigning the original var after construction has no effect on the delegation — the delegated calls keep going to the original instance.

Rationale

interface Bag { fun size(): Int }

class Wrapper(private var inner: Bag) : Bag by inner {  // misleading
    fun replace(b: Bag) {
        inner = b      // does NOT redirect Bag's methods
    }
}

The compiler captures inner at construction time. After replace, the field inner holds the new bag but the delegation still routes through the original. The mutability of inner only suggests redirection is possible; the runtime behaviour contradicts that.

Remediation

// Make the delegate target immutable to remove the false expectation.
class Wrapper(private val inner: Bag) : Bag by inner

If runtime redirection is actually required, replace the by delegation with explicit forwarding methods that read the current var value.

References