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.
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.
Replace the class or singleton object with a lambda expression that implements the interface’s single function.
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
// ...
}
}
val resource = loadResource() { // Compliant
// ...
}
val callback = ProgressCallback { // Compliant
// ...
}