Kotlin - Listeners are doomed

From the early days of Android, development was strictly done in Java, first using the aging and rough-edged Eclipse, then migrated to Android Studio (a customized version of IntelliJ IDEA from Jetbrains). With that change, the world of Android development got a little brighter, but we still used Java. Java was ok, but it was getting old.
On the other side of mobile development...
In 2014, Apple introduced Swift, making iOS development more functional. Apple gave Swift beautiful features that made iOS development a lot more productive, despite the problem of migrating the code from one Swift version to another. However, Swift 3 was introduced and Apple implemented ABI stability, which solved this problem.
You might be asking why i'm giving you this information. Well, it's important to the context in which Kotlin appeared. iOS was ahead in the functional game, until…

Jetbrains started working on a new language called Kotlin. By using the Java compiler, they made functional programming possible. Google saw this as an opportunity to give Android developers many new tools and make Android development more productive, just like on iOS did with Swift; in fact there are some similarities between both platforms now.

In my next posts, I'm going to explore Kotlin and how it will help any mobile developer do more work in less time.


Listeners are doomed

One of the things that are commonly used to handle async tasks in Java is Listener Interfaces, which are used to call a method and create an implementation of the interface with a callback. In Kotlin this idea is replaced by Lambda expressions or what the iOS developers know as Closures. These self-contained portions of logic are really powerful, and they even look similar:

Swift

{ var: String -> Void in
    var.uppercased()
}

Kotlin

{ var: String -> Unit
    var.toUpperCase()
}

The old way

interface MyUpperCaseListener {
    void handleString(String var);
}
//implementation
...
new MyUpperCaseListener() {
    void handleString(String var) {
        var.toUpperCase();
    }
}

See how similar Swift and Kotlin are? Both platforms infer the parameters. In Kotlin the return type is always inferred, in Swift, this only happens on single line closures.

With Kotlin, we can reduce the amount of code needed to handle a callback, from creating an interface with just one function to just an anonymous block of code that is directly written in the place where it needs to be used.

Download our Incubator Resources

 

WANT MORE?

We’re known for sharing everything!

HANDBOOK

Save more time, get more done!

FREE HANDBOOK

Innovate from the inside

Written by
Alejandro Moya 04 Mar 2019

Senior Mobile developer, devoted father and husband, love everything mobile and tech related.

YOU MIGHT ALSO LIKE

comments powered by Disqus