Yet Another Kotlin Article

Samuel Koprivnjak
AndroidPub
Published in
3 min readSep 9, 2017

I know, I know that there are dozen of tutorials and examples of Kotlin language application in Android development. But hey, this might still be useful to someone and you might get some ideas from my real life code examples. Here is a collection of code snippets and short descriptions that I’ve used in my recent project.

1. No More AsyncTask Boilerplate

This is my absolute favorite. In combination with Anko library, this background and main thread switching never looked so straightforward and simple. uiThread runs on the main thread and it is aware of activity lifecycle so no errors would happen if Activity is paused or stopped during task execution.

doAsync {
var result = expensiveCalculation()
uiThread {
toast(result)
}
}

2. Data Classes

Kotlin data classes are replacing writing of boring Java POJO classes.

Definition:

data class User(val username: String, val email: String, val provider: String = "Google")

Take notice that you can provide default values for class members (val provider: String = “Google”) if they are not explicitly provided.

Usage (with cool named arguments which can be used in any order):

User(username = "TestUser", email = "test_user@foreach.io", provider="Fb")

It has out of the box implemented methods:

equals(), hashCode(), toString() — format of “User(username=TestUser, email=test_user@foreach.io, provider=Fb)” and copy() method

3. When Expression

More readable replacement for switch case use cases, while also supports interesting if-else-if scenario.

when {
response == null -> toast("sign_in_cancelled")
response.errorCode == ErrorCodes.NO_NETWORK -> toast("connection")
response.errorCode == ErrorCodes.UNKNOWN_ERROR -> toast("unknown")
}

4. Scoping Function — Let

Nice idea to use as replacement for not null (profile != null) condition:

profile?.let {
user = UserAccount.getActive()
display = user?.display_name ?: "Not logged in"
}

This fancy looking “?:” symbol is called elvis operator which evaluates left side of it (user?.display_name) and if it is not null then elvis operator returns the value of that side, otherwise it returns default value from right side (“Not logged in”).

5. Enhanced Functional Foreach Loops

Quite often we have to loop over elements of list while staying aware of current index, and there is a nice and clean solution for that:

states.forEachIndexed { index, state ->
if (state.name == "Cambodia") {
chosenStateIndex = index
}
}

6. Extension Functions

Its definition feels little bit out of place (while you have to define extension function outside class body), but it seems like good replacement for Java static helper functions.

Definition:

class LocationHelpers {
}
fun LocationHelpers.getPoiIdFromSnippet(snippet: String?): Long {
return snippet?.substring(0,5)?.toLong() ?: -1
}

Usage:

LocationHelpers().getPoiIdFromSnippet(snippet)

7. Apply Extension Function

With apply() extension method you can quickly write initialization code for any object while not repeating variable name (user).

user = UserAccount().apply {
username = email
display = name
provider = authenticator
}

Conclusion

I would encourage to you to start using Kotlin language in Android development, while besides that it looks cleaner, shorter and more concise, it is actually fun to code in it.

And don’t forget that most of the errors in Java projects are NPE-s (NullPointerExceptions). So if using Kotlin language correctly there is great probability of minimizing the potential problems and significantly raising the quality of your codebase.

So, now stop reading and do some Kotlin coding :)

--

--

Samuel Koprivnjak
AndroidPub

Besides kicking volleyball, playing jazz piano, I design software, manage team and myself in the first place