Writing Android app with Kotlin
10 Nov 2014
When I read about Kotlin, I thought of it as a functional port of Java which is (100% interoperable with Java). I have been playing with Scala for a bit. The biggest trouble I had with Scala is wide range of semantic alternatives. But it seems like, Kotlin has a decisive approach towards making Java more functional and more compact for developers.
Kotlin does support Androi and they do have a very verbose documentation about Android support, So I went ahead and tried one simple list app with an adapter and a fragment, just to simulate a simple part of general Android application.
- Install Kotlin plugin available in Preferences for Android Studio.
- Add following classpath to the gradle script
- And add the dependency in the application gradle script
I started with writing a HackerNews listing app with simulated API calls (had to do it quickly).
Let’s dive into some code.
It’s the main activity (launcher) of the application.
Things I loved
- Kotlin has val, var keywords to separate out the final and variables.
- Nullable is always appended with a ‘?’. That hints the compulsions around null checks and method calls. Helps to avoid null pointers :-)
This is the fragment that contains list of posts.
Things I loved
- Functions are first class citizens. And this helps us to remove all those interfaces we end up creating to circumvent this problem in Java.
- In Kotlin, you have to write all the static methods separately inside an object. Most of the times the static methods are factory methods, and this helped me to make the code more readable. So I call each of the object inside the class as Maker, and write different factory method inside it. This is completely possible with Java by writing inner classes, but this being the semantics of the language, forces us to write the factory methods like this.
This is the model class containing info related with each post.
Things I loved
- Data classes have amazing inherent toString support. Great for logging
- Compact, more readable declarations for model classes.
This is the list adapter for post list view.
This all works well. The source code is available at https://github.com/akshaydeo/kotlin_android.
Some analysis of APK
- The very important thing to look at is, the number of classes inside your APK. Compared to Java based app, its gonna be huge. For example the application that I have created contains 3561 classes.Running proguard to strip out the unused classes is a must before creting a release build.
- Huge memory requirements during the builds. So you will have to change the VM preferences before using Kotlin as your Android development laguage. Mine were:
Important Links for Kotlin
I will be updating this post as I progress in analysing the side effects of using Kotlin for Android development.