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.