Kotlin example project ‚Sunshine reloaded‘

05 Feb 2016
by Artjom König

About a week ago I stumbled upon Kotlin and desided to rewrite the Sunshine project using Kotlin and some popular libraries like RxJava and Retrofit.

Let’s start with a very simple version. It should load 7 days forecast using the Openweathermap API and show it as a list. There are no menus, no navigation, no database… just a list with one entry per day. The current day should be highlighted (have another layout) and there should be a possibility to reload the data. The list is implemented with RecyclerView, the refresh with SwipeRefreshLayout. The data is loded using the Retrofit 2 Framework and I use RxAndroid for handling the response.

There are some Kotlin-related parts, that are interesting here. In my projects I normally use Butterknife for binding the Views. In Kotlin there are Kotlin Android Extensions, so instead of

you import the the properties generated by the Kotlin android extensions and use the Views referencing them by their id straight in your code:

It works for the ViewHolder, too, just look in the ForecastAdapter for the example.

Another interesting part of Kotlin are the extensions. iOS developer are already familiar with this technique, now you can use it for Android development, too. With extensions you can add functions to existing classes like this:

This function is added to the Long type of Kotlin and can be called on all Long values to format them to a String, if the value is a Unix timestamp (seconds since 1970). This way we can avoid introducing utility classes with static functions e.g. TimeUtils.formatUnixTimestampAsShortDate(long timeInMilliseconds), instead this you can just write myTimestamp.unixTimestampAsShortDate(). By the way, don’t use your own date/time formatting patterns, even if stackoverflow is full with such examples. Use Locale specific formats, so that your users see the date in the format of their country.

Another example for an extension is the convenient inflate function:

you can call it on every ViewGroup like this:

This version of the project can be found on Github.

Also published on Medium.

Appcube © 2017