Object Literal Lambda
ID |
kotlin.object_literal_lambda |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Kotlin |
Tags |
best-practice, code-style |
Description
Reports anonymous object : Interface { … } expressions that implement a
single-abstract-method interface (Kotlin fun interface) with exactly one
override. Such literals can be replaced by a lambda, which is the idiomatic
form fun interface was designed to enable.
Rationale
fun interface Action { fun run() }
fun call(a: Action) = a.run()
// Verbose
call(object : Action {
override fun run() = println("x")
})
fun interface was added so that callers could express the implementation as
a lambda. Using an anonymous object negates that benefit, adds boilerplate
(class name, override, function header, braces) and obscures the intent.
Remediation
fun interface Action { fun run() }
call { println("x") }
Replace the anonymous object with a lambda. If the implementation captures non-local state (e.g. has additional properties or multiple methods) it should remain an anonymous object — those usages are not flagged.