algorithms kotlin

Problem 5.9 from EPI -> Is number a palindrome?

Given a number, check if it is a palindrome or not, for example 121 => true, 122 => false, 2 => true.
There is an easy way, convert the number to string then reverse the string, if both strings are equal it is a palindrome, however that solutions takes up more space, to solve this problem in O(1) space take a look at this solution here. It basically checks how many digits a number has, then repeatedly takes the left most right digit and the right most digit and compares the two, if they don’t match at any step, return false, otherwise return true.

algorithms kotlin

Problem 5.11 from EPI -> Intersecting rectangles

Give a rectangle, does another rectangle intersects it? If it does print out the intersecting rectangle!
The tricks to detecting if they intersect is to treat x and y axis separately, and then combine both checks in to one.
The trick to getting the intersected rectangle is to realize that any of the two rectangles can be on the left or the right side, so taking max() and min() of both rectangle we can get a correct answer.
Take a look at this code

algorithms kotlin

Problem 5.8 from EPI -> Reverse digits of a number

Given a number like “123”, print out the reverse of that number like “321”!
There is a quick and easy way, convert the number to string and call string.reverse(), but it takes more memory than is neccessary.
A better way is to repeatedly take the most right number multiply it by 10 and add the next most right number, repeat until the number to reverse is zero.
Take a look at this code.
Happy coding!

blog kotlin productivity

Force yourself to use Kotlin standard library!

Java world vs Kotlin world

One of the main stumbling blocks I encountered when I tried to use Kotlin is how can start writing Kotlin code using Kotlin idioms, instead of just writing Java code with Kotlin syntax. To explain what I mean let’s imagine we want to filter a list of links, and extract only links that contain “.com” domain. That can be done in java with this:
This example repeats itself in Java code all the time, but with Kotlin now, there is no need to write code like this ever again.


In Kotlin there is a generic extension function that can do this for us, it is called, filter. To rewrite this example in Kotlin, it would look something similar to this:
How beautiful is that? And Kotlin has lots of these extension functions that will simplify our life when doing common operations on collections in our code.

Map and forEach

What if you need to transform a list of type String, into a list of TextViews, and append all those text views on a root view, how would you do it in Java?
Now, compare that to this Kotlin code that does the same thing:
Here .map was used for transforming a list of Strings into a new list of TextViews, and you can access each String with it keyword. Then forEach was used to iterate over the text view list and append each to the root view. But we can simplify this even more.


One of the main benefits of using built-in collection extension functions is chaining. We can now combine map with forEach:
But why stop there, lets chain from the beginning:
Now that is much simpler and easier to understand than the Java equivalent.

GroupBy and Any

GroupBy can be used to create hash maps, with the return value from the lambda as a key, and the object itself as the value.
Any is also interesting, if you apply it to the list you must supply a lambda that returns a boolean which then checks if that lambda returns true for any items in the list.

Think standard library

Every time you write a Kotlin code, ask yourself is this Java style of coding, or is there a better way to do this in Kotlin? And most probably there is, every time you do some operation on lists, think how can this be done with Kotlin standard library. For a list of all things related to collections explore this link. You can find documentation for map, forEach, filter and lots of other functions that can be applied to collections.


Mastering Kotlin will take some time, but the important thing is to always be on the lookout for ways to write code that utilizes Kotlin language features to the maximum.


What the hell are Kotlin class constructors?

A Kotlin world

In a Kotlin world, there are primary and secondary constructors, let’s start with a Kotlin primary constructor, the recommended constructor to use:
That is it, constructor keyword is omitted and the declaration goes after the class name. Class properties are declared as arguments in the constructor definition, and since they are public by default you can access properties by syntax.
The main constructor cannot contain code, all initialization is done inside init blocks, and there can be multiple init blocks:
Alongside the primary constructor, we have secondary constructors, and there can be multiple secondary constructors with different arguments just like in Java. Secondary constructors begin with a word constructor:
One thing to note is that before the second constructor is invoked, a primary constructor must be called with this keyword, that will force the execution the primary constructor and all init blocks to execute and all member initializations to be done, and then the secondary constructor will execute.
If you have multiple constructors you can delegate/call from one constructor to the next with this keyword, then pass the appropriate arguments.
So when to use the primary constructor, a secondary or an init block?


The primary constructor is the one you will use most of the time, and it has a nice short syntax, 90% of the time it is enough when declaring a new class.
Secondary constructors can be useful when a Kotlin code gets called from Java, an example of that would be when extending an Android View with a Kotlin class. In Kotlin you can declare default arguments, while in java you can’t, that is why secondary constructors are useful, you can create multiple constructors that require different parameters, a nice addition if you are calling Kotlin code from Java.
Init block can be used for, as its name suggests, default initializations that are required to run when an object gets created, because the primary constructor does not contain any expressions init blocks will serve as an extension to the primary constructor.

Order of execution

If you are like me, I was confused when I first saw init blocks, secondary constructors, primary constructor. What does execute first?
The first thing that gets executed is the primary constructor, then in order of placement either member initialization or init blocks, then secondary constructor:


As seen in the examples above, Kotlin offers multiple ways of doing things, from a simple primary constructor to multiple constructors that offer better interoperability with Java. Also, the init blocks that can provide a clear way of specifying what is important and what has to be run once an object is created.
If you find the article interesting comment below or share on social media, thanks.

blog design kotlin OOP

Kotlin extension functions

 A world without extension functions

Imagine a scenario, you are coding a java android app, and you are using java.util.Calendar class for data and time management. You realize that you need to convert a calendar instance into a pretty format like “4 minutes ago…” but you are out of luck since Calendar object has no method that returns pretty format like that. The most common solution to this problem involves creating a util function that does that. Something like this:
So what is the main problem with this solution? It goes against OOP principles. Accessing CalendarUtils class directly all over the project tightly couples your code to this utils class, and that is not a good thing.  It is impossible to switch later on to a different implementation of this class since its imported directly.
Another issue is testing, how can you test a class that directly imports a utils class? Tests written for this class will also test the utils class, and when you change that utils class, tests may break even if you did not touch your original class.

Object-oriented programming to save the day

A better way to solve this problem would be to use a wrapper around calendar object. Something like this:
Now, this is a much better implementation. We can create an interface around this class, provide multiple implementations, use dependency injection to provide this functionality to our app, a much better object-oriented solution.
What are downsides to this object-oriented implementation? It requires more code then the first solution, and it does almost the same thing. A whole class is created just to wrap a calendar object and provide one method on top of it.

A world with extension functions

For simple use cases, it would be nice to have some way of declaring functions that can be attached to some objects, and that function would have access to all properties of that object. So the effect would be similar to creating a wrapper class around that object, and we would not import that extension function all our code base, we would just call it upon the receiver object. It is still not a perfect solution but much better than creating utils classes.
Kotlin extension functions to the rescue! How would an extension function look like for the problem above?
The extension function is the second function in the snippet above, Calendar.minutesAgoFrom, and you can immediately recognize that in the name of the extension function we specify on which class we want to attach the method. In this case, it is the Calendar class. So every time we create a Calendar instance in our code minutesAgoFrom will be available on that Calendar instance. The second thing to notice is the use of this keyword inside the extension function. This is the main power of extension functions, it provides an access to all internals of the Calendar object, hence the use of this.timeInMillis.
Extension functions are a middle ground between a fully object-oriented solution and procedural coding with static utils classes.
To really appreciate the power of extension functions let’s look at the code below, taken from the Kotlin extension documentation.
How powerful is that? We just created an extension function that applies to all possible list types. Now every list in your app has a swap function that can swap elements no matter the list type.


This just scratches the beginning of what extension functions look like, in part 2 we will see some popular collections of extension functions and how they actually work behind the scenes.

android architecture blog design kotlin

Android architecture components with Kotlin


After Google announced android architecture components, it was, for the first time, a Google-approved android architecture guidelines. Before this, the whole community would try to come up with best ways to structure android apps. First, everyone tried to follow MVC pattern that Google sort of provided with Android. But MVC for android is very confusing, you have a controller who is a view also (Activity, Fragment). Then MVP came along. model view presenter architecture, which clearly separates responsibilities of views and presenters (controllers). The main idea was to define interfaces (responsibilities) for each view and its presenter, making the app much easier to refactor down the road, given the fact that you know exactly what are responsibilities of each screen. One downside for MVP is the total amount of interfaces you have to create and maintain.
When reactive java came along, it turned everything upside down. MVP did not fit quite well with rxJava, since data is reactive, you do not have to specify what happens when data changes, you just map it to the view and the view became reactive to its data. With reactive programming, you react to changes in the app, whether its user input or network fetching and the view is this dummy representation of that data. It turned out, that reactive programming is perfect for Android, since events are something that is very natural to mobile phones, it became much easier to write and maintain complex UIs with rxJava. So what are downsides to rxJava? Spaghetti code, if you can not recognize when to use rxJava, it is very easy to write spaghetti code.
So what exactly does architecture components bring to the table?

Architecture components overview

Before we look into what architecture components offer, what problems do they solve, let’s look at common issues Android developers face.

  • Configuration change (device rotation),
  • Synchronized UI with data
  • Fetching data from database
  • … (lots more)

Let’s start with the configuration change, what would be a proper way to solve this problem? In my opinion, I want no memory leaks :D, then I would like the data to survive the change, I don’t want to fetch data again just because a user rotated the screen. So we need some kind of lifecycle aware component which survives the configuration change, knows when it can update the activity, but also knows when to destroy itself when it is not needed anymore. This is exactly what ViewModel class is. With few lines of code, you can have a UI that reacts to data changes and also display the latest data when UI gets recreated.
What about UI synchronization? That is where LiveData comes in. Once you create a LiveData instance, you can subscribe to it, and receive updates every time you update that LiveData instance.
What about the database? There are plenty of ORM libraries out there, do we need another one? Well, what if you want an ORM which returns a LiveData, which you can subscribe to it, so when you insert new data into the database, you get updates immediately? That is where Room comes in.
Those are the building blocks of Android architecture components, but the question remains, what about Android architecture? These components serve a specific purpose, how to structure the whole app now?
Well, just follow MVVM architecture, the View reacts to ViewModel, which exposes Models for Views to use and update their representation. Instead of wiring the Views to Models manually, Data-Binding library can be used to that automatically. So what we described above is just a Google recommended/provided implementation of the required components for MVVM architecture.

Github repository

I made a Github repository for a sample project that uses Kotlin and android architecture components, check it out to see how everything fits together in one app. Here are the main specifications of the project in that repository:

  • ViewModel for reactive data binding
  • Room as ORM library
  • Paging Library as a reactive data source for adapters
  • Dagger 2 as dependency injection framework
  • Repository pattern for data fetching
  • Retrofit as a REST client

blog kotlin

Quick introduction to Kotlin coroutines part 2

If you have not read part one of this series, please read it first, it explains the main idea behind Kotlin coroutines.

Error handling

If you read the part one of this series, you may notice that error handling was not covered as a topic at all, so in this post, we will go through techniques you can utilize to handle errors that may occur inside coroutines.


The main idea introduced in part one of this series is the idea of async code written as a synchronous code and if you think about it, how would you handle errors in a sync style code, you catch exceptions. Same idea here, we can surround code that throws an error inside try/catch block, and handle error states in your async code. Let’s see an example of a retrofit network call.
As we can see in the example above, we surrounded the retrofit method execute with try and catch blocks, and two exceptions are caught that execute method can throw, IOException and RuntimeException. Why just these two exceptions? If you look at the documentation for execute method, you can see that execute method can throw only those two exceptions. In case an exception is thrown, the user will be notified, and that part of the code runs on the main thread.
A better way would be to pass in an exception handler that will be called once the launch coroutine encounters and exception.

Async vs launch builder

In part 1, we mainly used launch coroutine builder as our main coroutine block, and one problem with launch builder is the exception handling, if an exception is not caught inside a coroutine, the whole app will crash. Kotlin provides another coroutine builder, Async builder, which behaves differently in few ways. One way in which it differs is exception handling, async block just ignores thrown exceptions if they are not caught resulting in a non app crash scenario. Here is a way to catch an exception with async block


What if you need to cancel a coroutine, for example, the android activity gets paused or destroyed, and the coroutine result is no longer needed?


All coroutine builders return a job, which can be canceled at any point by calling job.cancel(). What is interesting with Kotlin coroutines is the ability to specify a parent job as a context for multiple coroutines, and calling cancel() on the parent coroutine will result in all coroutines being canceled, very convinient. In all examples above you may notice the parentJob passed in in every coroutine, and calling parentJob.cancel() inside onPause() activity method results in all coroutines being cancelled.

Hooking into callback code

The last thing I want to talk about is hooking into code that is async but uses callbacks to handle the suspension of the flow. For example, firebase database uses callbacks to inform the caller an operation has completed. In that case, you need to bridge between a Kotlin coroutine and a callback listener. SuspendCoroutine to the rescue! A special coroutine which will be suspended by default, and you call resume on it inside the callback method. Below is an example from one of my apps that uses google firebase as a backend.
This getBooleanValue can be used inside any coroutine and will behave as any other suspend function, hence creating a bridge between Kotlin coroutine and callback.


I have created a sample app that uses all exception handling cases shown in this blog post on this Github repository.
If you liked the article share it if you loved it comment below :).

blog kotlin

Quick introduction to Kotlin coroutines part 1


So first, let me start this article by saying that I spent few years developing Android apps in Java, and the one thing that I used to do frequently was to separate layers of abstraction with interfaces. And for example in the networking layer, I end up writing lots of interfaces that declare methods, with a listener parameter, and this listener will implement some onSuccess and onFail methods. What this leads to is lots of nested callbacks where I go few layers deep into callbacks and onSuccess and onFail blocks, something like the code below.
Then Kotlin came along, got supported by Google officially and suddenly, everyone went mad, and for a good reason, it is a modern swift like, compiled, language, which is a huge step up from the Java world. And one thing caught my eye when I first read through the Kotlin documentation, Kotlin coroutines. I thought, well this for me, the one thing I can use right now to avoid my callback hell problem. So I jumped straight into it. Here is my journey to understanding what Kotlin coroutines are.

Asynchronous code as a synchronous code

The header above is the essence of what coroutines are, it is a way to declare a block of code in which every line suspends execution of the block, what does that mean? Well, you simply don’t have to provide a callback for long-running functions, you just add that function to a coroutine and the coroutine will suspend its execution until that method returns hence no more callbacks!
Look at the code below:
This is my interface for the data storage contract in Kotlin, no listener interface needed, you will notice the suspend keyword in front of all methods, that is a special Kotlin syntax to indicate this function should be run from a coroutine block or another suspend function, basically anything that involves a network call or a CPU intensive task should be placed inside suspend functions and then consumed from a coroutine block.

Coroutine builders

If we want to call our suspend function, we need to pass it to the coroutine builder, which will do the heavy lifting for us, and ensure that the code inside that builder will run on a thread of our choice, for example, let’s use launch coroutine builder:
That’s it, you simply consume your suspend function inside the launch block and you are good to go.  Every time a suspend function is encountered, the execution of this coroutine block suspends, waiting for the function to return. Any code above our getStringValue method call will be executed first, then our function, then the rest of code below, no callbacks! So on which thread will the above launch block execute? Obviously, we want it to execute on a background thread and we want to update the UI with values from our suspend functions.

Coroutine context

Every coroutine builder can have a context in which to run, the main thread, or some other thread, if no context is specified, like the example above, it’s the CommonPool of threads, meaning it will run on a separate thread from the main thread of the app. So if the code above is running in the background thread, how to update the UI then? To update the UI there is one more step that needs to be done, and its another launch block with a coroutine context specified, like the example below:
Everything inside the second launch will use the main thread event dispatcher, that will post our update on the main thread. What is cool about this is that the second launch block will also wait for the code above to execute and once it does execute, the value variable will be set and we can safely update our UI. Coroutine context is simply a coroutine dispatcher, which controls on what thread the coroutine block is running.

Coroutines are lightweight threads

Coroutines run on threads and can suspend its execution without blocking the thread it runs on, so the thread execution is not tied to the coroutine execution, they operate separately. If you think about it, callbacks are almost the same thing, they suspend execution and continue once the result is available, but have a boilerplate syntax and require you to repeat yourself everytime you want to suspend an execution.

Launch vs Run coroutine builder

One problem with nesting coroutines is that every coroutine block will have its own execution line, meaning the second coroutine block will not suspend the parent coroutine. There is a better way of writing the code above, since getStringValue  function returns a value, we can use a run coroutine builder to return a value from a suspend function, hence we can start on the main thread, and invoke our getStringValue function inside a background thread, the other way around from the example above.
The main difference between launch and run coroutine builder is the return value, launch has none while run has, so in this case, we will assign our variable value to whatever the result value of the run block is.
I specified a dispatcher for run block intentionally since nested coroutines take the parent coroutine context if not specified, and we do not want that in this case, we want the run block to execute on a background thread.
I believe this is all you need to know to start playing around with coroutines, don’t hesitate to open android studio and write some coroutines!

Further reading

Coroutines can do much more if you need it, there are many different coroutine builders, channels, synchronization options etc. The best introduction to coroutines is the official Kotlin coroutines guide on Github, don’t hesitate to read it, you will find lots of gems in there.


To use coroutines in your project, you need a couple of additions to your build grade file, mainly these two lines:
The coroutines-android dependency is for the special UI context that can be passed to coroutine builders that uses the main thread dispatcher to dispatch events on the main thread.
Then you have to tell Gradle that we will use coroutines in the app by adding these lines to the app build Gradle file:

Github sample project: Fibonacci counter

I wrote a simple Android app in Kotlin, that implements a Fibonacci counter with coroutines. Check it out on Github, clone the repository and play with it and most importantly have fun!


This is a part one of two-part series, check out part two of the series.