74 lines
1.8 KiB
Plaintext
74 lines
1.8 KiB
Plaintext
== 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
|
|
|
|
[source,kotlin]
|
|
----
|
|
fun interface ProgressCallback {
|
|
fun progressChanged(percent: Double)
|
|
}
|
|
|
|
fun loadResource(callback: ProgressCallback) {
|
|
// ...
|
|
}
|
|
----
|
|
|
|
[source,kotlin,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
val resource = loadResource(object: ProgressCallback { // Noncompliant
|
|
override fun progressChanged(percent: Double) {
|
|
// ...
|
|
}
|
|
})
|
|
|
|
val callback = object: ProgressCallback {
|
|
override fun progressChanged(percent: Double) { // Noncompliant
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,kotlin,diff-id=1,diff-type=compliant]
|
|
----
|
|
val resource = loadResource() { // Compliant
|
|
// ...
|
|
}
|
|
|
|
val callback = ProgressCallback { // Compliant
|
|
// ...
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://kotlinlang.org/docs/fun-interfaces.html[Kotlin Docs, Functional (SAM) interfaces]
|
|
|
|
=== Articles & blog posts
|
|
|
|
* https://www.baeldung.com/kotlin/sam-conversions[Baeldung, SAM Conversions in Kotlin]
|