
Before reading these tips, you should read the Kotlin documentation and learn the language yourself at try.kotlinlang.org
. Since these tips are aimed specifically at using Kotlin in the context of Android development, you should also have experience with the Android SDK. It is also advisable to familiarize yourself with the Kotlin plugin and the use of Kotlin with Android Studio from JetBrains (creators of Kotlin)
Kotlin Basic Android Tips
Lazy Loading
Lazy loading has several advantages. For example, such:
- You save startup time because loading some data is delayed until it is needed. This is especially true for Android, because the user will see the contents of the application faster instead of a long wait time for launching and watching the download tap.
- You save memory, because the resource is loaded into the device’s memory only upon request. This is especially important for mobile platforms, because the resources of mobile phones are quite limited.
For example, if you are creating a shopping application in which users will mainly be guided by your choice, then lazy loading can be configured on the actual shopping API, for example, something like this:
val purchasingApi: PurchasingApi by lazy { val retrofit: Retrofit = Retrofit.Builder() .baseUrl(API_URL) .addConverterFactory(MoshiConverterFactory.create()) .build() retrofit.create(PurchasingApi::class.java) }
The result of using such a lazy download will be that if the user does not try to make a purchase in the application, you will not download it and use unclaimed resources.
Also lazy loading is a good way to encapsulate initialization logic, for example:
val bounds: RectF by lazy { RectF(0f, 0f, width.toFloat(), height.toFloat()) }
As soon as the first call is made, an instance of RectF is created based on the current width and height of the view, which eliminates the need to create it separately and set this object.
Custom getters and setters
To read custom settings in the Kotlin language, a structural model with specified user behavior is used to obtain and set fields. When using models for specific frameworks, such as the Parse SDK, you select values ​​that are not local class variables, but that are retrieved and stored using a custom method, for example, from JSON.
Using user-defined acquisition and installation methods, we can simplify access, for example:
@ParseClassName("Book") class Book : ParseObject() {
Retrieving these values ​​will be similar to using property access syntax in other models, such as:
val book = api.getBook() textAuthor.text = book.author
Now, if you need to transfer your model from Parse to some other data source, the code practically does not need to be changed.
Lambda
Lambdas reduce duplication of lines of code in the source file and allow the use of functional programming. Although lambdas are currently used by Android, Kotlin takes them to a new level, ensuring that you don’t have to deal with Retrolambda or change the way you build.
For example, listening to a file would look something like this:
button.setOnClickListener { view -> startDetailActivity() }
And this is how it works with return values:
toolbar.setOnLongClickListener { showContextMenu() true }
In the Android SDK, quite often there is a need to implement one of these methods. The lambda copes with this with a bang.
Data classes
Data classes simplify classes by automatically adding the
equals()
,
hashCode()
,
copy()
and
toString()
methods. They clarify what data should be used in the model, separating data from logic.
For example, here is such a data class:
data class User(val name: String, val age: Int)
That's all. Nothing more is needed for his work. If you use data classes with something similar to Gson or another JSON type library, you can create a default constructor with default values, for example:
data class User( @SerializedName("name") val name: String = "", @SerializedName("age") val age: Int = 0 )
Dataset Filtering
In working with the API, the need to process collections constantly arises. Most often, they need to be filtered or modified contents.
Using filtering collections Kotlin, you can make the code simpler and more understandable. You can specify the contents of a list of results by filtering collections, for example, like this:
val users = api.getUsers() val activeUsersNames = items.filter { it.active } adapter.setUsers(activeUsers)
Kotlin's built-in collection filtering methods are very similar to methods used in other programming languages ​​like Java 8 or when working with Swift collection types. Unified methods of filtering collections simplify mutual understanding when communicating with employees about the need to perform specific operations to obtain and display the necessary lists of items.
This concludes the first part of the article and invites you to attend a free webinar on the topic: “Unit testing in Android” .