The last part of the Kotlin Koans tutorial had me use Object Expressions to sort an ArrayList. I observed that this could have been done with a lambda expression and I was correct.
This portion of the tutorial discusses implementing an interface with one abstract method. Kotlin calls such interfaces a SAM interface (Single Abstract Method). Whenever a developer is working with a SAM interface, they are free to use a lambda expression rather than an Object Expression.
Here is the Kotlin code that uses a lambda expression
fun task11(): List { val arrayList = arrayListOf(1, 5, 2) Collections.sort(arrayList, { x, y -> y.compareTo(x) }) return arrayList }
I should point out that Java 8 supports lambda expressions now also. Java calls SAM interfaces Functional interfaces. You can even add a @Functional annotation to such interfaces in Java.
I don’t see any huge advantage to Kotlin lambdas over Java ones at this point. Of course, Android developers may appreciate Kotlin’s lambda support.
You can view part 11 here.
One thought on “Kotlin Koans—Part 12”