Why is this an issue?
Functional interfaces can be instantiated from lambda expressions directly. If the only purpose of a class or a singleton object is to implement a
functional interface, that class or object is redundant and should be replaced with a lambda expression.
What is the potential impact?
Complexity
When an interface is declared functional, SAM conversion is enabled for that interface. This means that any lambda expression that matches
the interface’s single function’s signature can be converted into an instance of the interface without the need for an explicit class or singleton
object to implement the interface. This change makes the code more concise and easier to read.
How to fix it
Replace the class or singleton object with a lambda expression that implements the interface’s single function.
Code examples
Noncompliant code example
fun interface ProgressCallback {
fun progressChanged(percent: Double)
}
fun loadResource(callback: ProgressCallback) {
// ...
}
val resource = loadResource(object: ProgressCallback { // Noncompliant
override fun progressChanged(percent: Double) {
// ...
}
})
val callback = object: ProgressCallback {
override fun progressChanged(percent: Double) { // Noncompliant
// ...
}
}
Compliant solution
val resource = loadResource() { // Compliant
// ...
}
val callback = ProgressCallback { // Compliant
// ...
}
Resources
Documentation
Articles & blog posts