P4@ Tech topic #1 - "The Kotlin way"
This month we asked our Android-expert Mohamed Moamen to share some of his thoughts about writing code in Kotlin.
Read some of his tips below:
Kotlin is a fast, safe, lightweight, and modern programming language and any chunk of code written in Kotlin is much smaller and looks simpler compared to Java so let’s write Kotlin the Kotlin way.
It has been more than 5 years since Kotlin started booming. Are you still writing code in the Java way? If yes, don’t worry you are not alone. I will give you some simple tips and tricks on how to avoid that - but first let us recap why many Android developers still think in a Java way.
In 2017 Google promoted Kotlin to be the first option for Android development, starting from this date many Android developers took the decision to move carefully to Kotlin.
The most famous debate these days among Android developers, is that after integrating Kotlin into existing Java based Android projects, should we continue using the same Java codebase? or make a new Kotlin codebase?
It is a hard decision to take, especially If you are working in a mature project having a good customer base, so integrating Kotlin is a low priority task in the backlog, so for many teams keeping the Java code base seems to be the smartest decision, but this was the start of `coding Kotlin the Java way' curse.
So how can we get over this curse? In the rest of the article I will list some tips to follow while coding Kotlin. Null-safety and data classes and sealed classes is covered extensively elsewhere, instead I’ll direct the tips more towards Kotlin coding style and best practices.
1. Extensions
Having lots of utils packages in your project is the first indicator that you are typing Kotlin in a Java way. Try as much as you can to avoid creating utils and replace it by extensions.
// bad way object FloatUtils { fun getRound(number: Float): Float { // code } fun toHex(number: Float): String { // code } } // Kotlin way val Float.round get() = // your code val Float.hex
get() = // code
2. More Extensions
Having any logic classes is a bad sign also, In this context, I am using the phrase “logic classes” to refer to classes that transform data from one shape to another.
For example, imagine that you have this API model and you would like to display the user full name and age.
data class User( val firstName: String, val secondName: String, val surname: String, val birthDate: String
)
One of the Java ways to map this data, is to create a new logic class and pass the `user` model to the constructor to map the data but following the same way in Kotlin is not the right way, use extensions instead. It will reduce the written code and be easier to call.
// bad way class UserLogic(private val user: User) { fun getFullName(): String { return userResponse.firstName + userResponse.secondName + userResponse.surname } fun getAge(): String { return birthDateToAge(birthDate = userResponse.birthDate) } } // kotlin way val User.age get() = birthDateToAge(birthDate = birthDate) val User.name get() = firstName + secondName + surname
3. Collection specific operations
Why are we using for loops? Most likely to iterate collection to (find, remove, filter, ..etc). Kotlin introduced tons of collection specific operations for whatever you can imagine, so every time you find yourself about to write for loops stop yourself and search for operations to do what you need.
list.find { it.whatever == "xxx" } list.first { it -> it.whatever == "xxx" } list.filter { items -> items.whatever == "xxx" } list.removeIf { it -> it.whatever == "xxx" } // that's a brilliant one ;) map.filter { it.key == "xxx" } map.filter { it.values == "xxx" } map.filterValues { it == "xxx" } sequence.any { it == "xxx" }
sequence.filter { it == "xxx" }
4. Optional function parameters
Heavy usage of overload is a Java thing, especially to add or remove only one function argument.
fun getData(id : Int){} fun getData(id : Int , category : Int){} Optional parameter should be enough in cases like that
fun getData(id : Int , category : Int = defaultValue){}
Some final thoughts: By following these simple points and having code review as a main process of your workflow, your code will improve in very little time.
//Mohamed Moamen, TekOps expert Android & Android Consultant - P4@ IT Cloud