Another blog on“why Kotlin”? cliché? Not really. This is more like a “why not Kotlin?” kind of blog post. This blog is my attempt to convince android app developers to migrate to Kotlin. It doesn’t matter if you have little or no knowledge of Kotlin, or you are an iOS developer who worships swift, read along, I am sure Kotlin will impress you (if not my writing).
I am going to show some of the amazing features of Kotlin programming language that makes development so much easy and fun. And makes the code so readable as if you are reading plain English. I read somewhere that “Programming language isn’t for computers, computers understand only 1s and 0s, it is for humans” I couldn’t agree more. There is a learning curve, sure, where isn’t? It pays off nicely. Kotlin makes us do more with fewer lines of code, kotlin makes us productive.
Lets quickly walk over some of the obvious reasons for migrating to Kotlin:
- Kotlin is one of the officially supported languages for android app development as announced in Google IO 2017.
- Kotlin is 100% interoperable with Java. Which basically means Kotlin can use Java classes and methods and vice versa.
- Kotlin has several modern programming language features like lambdas, higher order functions, null safety, extensions etc.
- Kotlin is developed and maintained by JetBrains, which is the company behind several integrated development environments that developers use every day (or IDEs like IntelliJ IDEA, PyCharm, PhpStorm, GoLand etc).
This is available all over the internet. This is the content of “Why Kotlin” category of blogs.
Let’s talk about something a little more interesting.
Higher Order Functions:
Kotlin functions are first class citizens. Meaning functions can be stored in variables, passed as arguments or returned from other functions. A higher-order function is a function that takes a function as a parameter or returns a function.
This may sound strange at first. Why in the world would I pass a function to another function? (or return a function from another function) It is very common in various programming languages including javascript, swift, python (and Kotlin apparently). An excellent example of a higher function is the map. The map is a higher order function that takes in a function as a parameter and returns a list of results of applying the given function in each item of the original list or array.
https://gist.github.com/drulabs/835ee8799d301591f1aea9ab739c88e3
checkout the map function above in line 3. It applies the stringStrirrer() function to each item of x. The result of the map operation is in line 4 above.
Data classes:
Java POJOs or Plain Old Java Objects or simply classes that store some data require a lot of boilerplate code most of the times, like getters, setters, equals, hashCode, toString etc. Kotlin data class derives these properties and functions automatically from properties defined in the primary constructor.
https://gist.github.com/drulabs/22c9d006824fae0f8526cdde4c42bd9d
Dealing With Strings:
Kotlin standard library makes dealing with strings so much easier. Here is a sample:
https://gist.github.com/drulabs/bb230439006fe47cceb58ac49393cf3a
No helper classes, public static methods or StringUtils is required. We can invoke these functions as if they belong to String class itself.
Dealing with Collections:
Same as String, the helper methods in “java.util.Collections” class are no longer required. We can directly call “sort, max, min, reverse, swap etc” on collections.
Consider a bank use case. A bank has many customers, a customer does several transactions every month. Think in terms of objects:
As it is clear from the picture above, a bank has many customers, a customer has some properties (name, list of transactions etc) and several transactions, a transaction has properties like amount, type etc. It will look something like this in Java:
https://gist.github.com/drulabs/7cf2e362e196e9f4a66585088b019f6f
Find the customer with minimum balance:
https://gist.github.com/drulabs/676b4f2243b1e9e88294101e6d04d586
I don’t know about you but I think the Kotlin way is much more clean, simple and readable. And we didn’t import any helper class for that (Java way needed Collections class). I can read it as plain English, which is more than what I can say for the Java counterpart. The motive here is not to compare Java with Kotlin, but to appreciate the Kotlin Kronicles.
There are several functions like map, filter, reduce, flatmap, fold, partition etc. Here is how we can simplify our tasks by combining these standard functions (for each problem statement below, imagine doing it in Java):
https://gist.github.com/drulabs/e57ed00b25f13b2d768e446d76fdc882
As it is clear from the above gist, we can solve mundane problems with much fewer lines of code. Readability wise I just love it. Above code explanation here:
- FlatMap: Returns a single list of all elements yielded from results of transform function being invoked on each element of the original array (in above cases the transform function returned list of transactions by each individual user)
- Filter and SumBy: Here we combined filter and sum by operations to write a one-liner code to find the total amount deposited and withdrawn from the bank considering all customers.
- Fold: Accumulates value starting with the initial value (0.0 in our case) and applying operation (when statement above) from left to right to current accumulator value and each element. Here we used fold and when to find the net amount deposited in the bank considering all deposits and withdrawals.
- Partition: Splits the original array into a pair of lists, where the first list contains elements for which predicate (the separation function in this case) yielded true, while the 2nd where it yielded false. Of course, we can filter twice, but this is so much easier.
So many complex operations simplified by the Kotlin standard library.
Extensions:
One of my favourite features. Kotlin extensions let us add functionality to a class without modifying the original class. Just like in Swift and C#. This can be very handy if used properly. Check this out:
https://gist.github.com/drulabs/a120086002c4b30e9beccec63d7866b4
In the above code, we just added a new function called “toINR()” to Kotlin’s Double type. So we basically added a new function in Kotlin’s primitive type, how about that ?. And it is a one-liner function, no curly braces, return type, return statement whatsoever. Noticed that conciseness did you?.
Since Kotlin supports higher order functions we can combine this with extension functions to solidify our code. One very common problem with android development involving SQLite is, developers often forget to end the transaction. Then we waste hours debugging it. Here is how we can avoid it:
https://gist.github.com/drulabs/426317a468b12a9a31a7bcdbf0a53670
We added an extension function called “performDBTransaction” in SQLiteDatabase. This function takes a parameter that is a function with no input and no output, and this parameter function is whatever we want executed in between begin and end transactions. This function calls beginTransaction() then the passed operation and then calls endTransaction(). We can use this function wherever required without having to double check if we called endTransaction or not.
I always forget to call commit() or apply() when storing data in Shared Preferences. Similar approach:
https://gist.github.com/drulabs/7fe102e27c9168c5c5783dce7d9ef6c6
extension function persist() (line 9 above) takes care of it. We are calling persist() as if it is a part of SharedPreferences.Editor.
Smart Casts:
Going back to our bank example. Let’s say the transaction can be of three types as explained in below figure:
NEFT transaction has fixed charges, IMPS has some bank-related charges. Now we deal with a transaction object, the super class “Transaction”. We need to identify the type of transaction so that the transaction can be processed accordingly. Here is how this can be handled in Kotlin:
https://gist.github.com/drulabs/1c9526320f4802fbc7540bf1ccbefa5a
Epilogue:
As developers, we need to focus on stuff that matters, the core part, and boilerplate code isn’t one of them. Kotlin helps in reducing boilerplate code and makes development fun. Kotlin has many amazing features which ease development and testing. Do not let the fear of the unknown dictate your choice of the programming language; migrate your apps to kotlin now. The initial resistance is the only resistance.
I sincerely hope you enjoyed the first article of this Kotlin Kronicles series. We have just tapped the surface. Stay tuned for part 2. Let me know if you want me to cover anything specific.
Got any suggestions? shoot below in comments.
What is your favourite feature of Kotlin?
Keep Developing…