Take a look at some of the most useful kotlin tips for developing Android apps. Before reading this, it is required you have a good knowledge of kotlin, experience in working with Android SDK. The Android Application development service providers must also be familiar with the Kotlin plugin and using kotlin with Android studio.
Without further ado lets jump to initial kotlin tips for Android
Lazy loading
Lazy loading is extremely useful as it results in faster startup time. When the user opens the app, it opens up immediately without the user having to wait.
For example when creating a shopping app, you can have the actual purchasing API be lazy loaded.
val purchasingApi: PurchasingApi by lazy {
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(MoshiConverterFactory.create())
.build()
retrofit.create(PurchasingApi::class.java)
}
It is also a good way to encapsulate initialization logic
// bounds is created as soon as the first call to bounds is made
val bounds: RectF by lazy {
RectF(0f, 0f, width.toFloat(), height.toFloat())
}
Lambdas
Lambas reduce the line of code in a source file.
An on-click listener looks something like this
button.setOnClickListener { view ->
startDetailActivity()
}
It even works with return values.
toolbar.setOnLongClickListener {
showContextMenu()
true
}
Collection filtering
One comes across collection filtering while working with API. The collection filtering in Kotlin adds more clarity and makes code more Succint. Something like this
val users = api.getUsers()
// we only want to show the active users in one list
val activeUsersNames = items.filter {
it.active // the "it" variable is the parameter for single parameter lamdba functions
}
adapter.setUsers(activeUsers)
Custom Getters/setters
By using custom Getters/setters, the access can be simplified.
Something like this
@ParseClassName("Book")
class Book : ParseObject() {
// getString() and put() are methods that come from ParseObject
var name: String
get() = getString("name")
set(value) = put("name", value)
var author: String
get() = getString("author")
set(value) = put("author", value)
}
Global constants
When the scope needs to be global, kotlin provides best ways to do so without having to go through a constant class.
package com.savvyapps.example
import android.support.annotation.StringDef
// Note that this is not a class, or an object
const val PRESENTATION_MODE_PRESENTING = "presenting"
const val PRESENTATION_MODE_EDITING = "editing"
They can be used as constants anywhere in the project
import com.savvyapps.example.PRESENTATION_MODE_EDITING
val currentPresentationMode = PRESENTATION_MODE_EDITING
Leveraging let
Leveraging let allows Android App development providers execute a block if the value of the object is not null. For example this is how it looks like in Java.
if (currentUser != null) {
text.setText(currentUser.name)
}
And in Kotlin, it looks something like this.
user?.let {
println(it.name)
}
Extensions
Adding extensions is an intermediate kotlin tip. Using extensions, you can add to the functionality of a class without having to Inherit from it. With the extensions, you can accomplish this easily.
fun Activity.hideKeyboard(): Boolean {
val view = currentFocus
view?.let {
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE)
as InputMethodManager
return inputMethodManager.hideSoftInputFromWindow(view.windowToken,
InputMethodManager.HIDE_NOT_ALWAYS)
}
return false
}
Data classes
Data classes simplify classes, adding copy(), equals(), and toString(),hashCode(),methods automatically.
For example, take a look at this data class.
data class User(val name: String, val age: Int)
With inheritx, you don’t run the risk of goof-ups and errors. We have been in business for 6 years and have arguably built the best client portfolio mobile app development and services.
We have a handpicked team of developers, designers, who work across Android, iOS and phone gap platforms. For more tips on kotlin, contact us now.
Leave Comment