Week #1 challenge: Kotlin in Android
More or less one week ago, I announced my 52 weeks, 52 projects challenge. In the first week, I tried native Android development in a language called Kotlin. If you have seen what Apple is doing with Swift, JetBrains (the team behind IntelliJ and Kotlin) is doing the same thing for Android developers: giving developers a simpler way of developing applications.
Kotlin is a statically typed programming language, targeting JVM and Android, and can also be used for front-end web development. It’s a known fact that Android developers are stuck with Java 6 (in most devices): no lambdas, using the old Single Abstract Method (SAM) interfaces for achieving functional programming, doing defensive programming against the freaky NullPointerException
s (heh). Kotlin is the solution, by bringing cool features like lambdas and string templates that look like those of Swift, range expressions, null safety, extension functions and other features. There is a strong reason why some people are calling Kotlin “the Swift for Android”.
The application I developed was a simple ToDo application which you can use as reference and fork it if you want to play around with it (send a PR if you want to improve it). The whole application is writen in Kotlin, excluding two Java test classes which are automatically generated by Android Studio. The first Kotlin function I wrote was this:
fun createUriMatcher(): UriMatcher {
var matcher: UriMatcher = UriMatcher(UriMatcher.NO_MATCH)
val authority = TaskContract.CONTENT_AUTHORITY
matcher.addURI(authority, TaskContract.TASK_PATH, TASK)
matcher.addURI(authority, "${TaskContract.TASK_PATH}/#", TASK_WITH_ID)
return matcher
}
It is a part of the Content Provider I wrote for the application. It is simple, elegant, more readable and faster to write than Java. But it comes with a price. Kotlin compilation time is longer than that of Java. It includes a runtime in the APK file that is created when the app is compiled, so it increases the APK file size. Also, Kotlin doesn’t work very well with Dependency Injectors like Dagger: you can’t use annotations (yet?) in Kotlin.
If you’re interested to see a workaround with Kotlin and Dagger, check this project: damianpetla/kotlin-dagger-example
And that’s it for the first week! If you have anything to ask me about Kotlin or this project, let me know in the comment section below. I will also write an article on SitePoint about how to create a Kotlin application in Android, so stay tuned.
UPDATE: You can now read my tutorial on how to build the application on SitePoint: Streamline Android Java Code with Kotlin