Top 5 Kotlin features for better readability
Named arguments
In terms of readability, this is by far my favorite Kotlin feature.
Let’s take a look at how we can make an instance of a class without using named arguments:
With named arguments:
By looking at the code you can tell what each of the arguments is used for, also the order of the declaration is up to you! Even better we don’t have to change anything if the order of the constructor’s arguments changes! It also makes your pull requests look cleaner and easier to understand.
Trailing commas
In Kotlin we can add a comma after the last argument
Now let’s say that our Car needs to have heated seats as well:
Now it’s time to make our pull request. Let’s compare the differences with and without trailing commas:
With the usage of trailing commas, we have just 1 change whereas without a trailing comma we have 3 changes!
Safer class casting
In Java, if we want to cast a class in a safe way we probably would come up with the following code:
As you can see we can’t escape the try-catch block. If we do so we would get “java.lang.ClassCastException”
Thankfully in Kotlin we can skip the try-catch block and use the “as?” operator
If the casting fails the expression returns null but since we are using the safe call operator the meow function would never get executed. If we would like to do more things with our casted object we could use the scoped function called let:
Take If
Any object in Kotlin has the takeIf function predefined. TakeIf is a function that accepts a predicate as an argument and returns the object if the predicate returns true, otherwise it returns null.
Also
Also or also(block: (T) -> Unit): T
is another scoped function in Kotlin. We receive as an argument the context object and the return value of .also is the context object itself.
Here we have a class that reads a string value from a local database. When we read from the local database we are returning the read value and also cache it in the cachedValue variable for later usage.
Which is your favorite Kotlin feature that makes your code more readable? 🙂