dvas0004 / NerdNotes

A collection of notes: things I'd like to remember while reading technical articles, technical questions I couldn't answer, and so on.
12 stars 0 forks source link

SAM conversions #46

Open dvas0004 opened 5 years ago

dvas0004 commented 5 years ago

In java, many libraries (such as the Android SDK), use interfaces which define a Single Abstract Method (a.k.a SAM), for example, in the below interface named Adder, we have a single method called add:

interface Adder {
    Integer add(int a, int b);
}

In java, we'd implement it like so:

public class myAdder implements Adder {
        public Integer add(int a, int b){
            return a+b;
        }        
}

However in Kotlin, the SAM conversion feature allows us to more do the above more concisely by passing in a lambda whenever an interface has just one method, like so:

val myAdder = Adder{ a,b -> a+b }
//or more concretely...
val runnable = Runnable { println("This runs in a runnable") }

However... SAM conversions can only be used with JAVA interfaces, not kotlin interfaces

dvas0004 commented 5 years ago

https://kotlinlang.org/docs/reference/java-interop.html https://code.tutsplus.com/tutorials/quick-tip-write-cleaner-code-with-kotlin-sam-conversions--cms-29304