Welcome to Our Website

Kotlin Tips for Android development

kotlin_android_development_tips

Kotlin was developed by JetBrains in 2010. They initially released it under the name Project Kotlin in July 2011. They needed a language that was concise, elegant, expressive, and also interoperable with Java, as most of their products were developed in Java, including the Intellij Idea.

Kotlin a modern statically typed programming language. It is expressive and concise. Kotlin offers many features that make code lesser and readable. In this blog, we will re-write the code in the Kotlin way and see how Kotlin makes code more concise and readable.

Related Post

https://devblog.link/kotlin-and-rx-kotlin-in-android/

Lazy Loading

Access to the Lazy Loading variable can help to improve the pace of the start-up time as it delays loading procedures. The use of Kotlin on an Android app can help to accelerate the process in comparison to a server application. Lazy loading can improve the loading pace for its user to gain faster access to the site. Lazy loading loads the resource in the memory when asked for access. The limitation in the shared resources of the phones must prioritize memory usage on Android platforms. For instance, during the development of a shopping app, the viewers might browse a particular choice, and the original purchase API can be lazy-loaded. In like manner, if a user overlooks an app, its PurchasingAPI will not load, which will save the memory resources. 

Initialization logic can also be encapsulated in a better way through lazy loading. Through the initial reference to bounds, the height and width of the view are used to create the RectF rather than building it up from scratch.

Null Safety With the Elvis Operator

The Elvis operator, ?:, provides null safety to your code. It can be used to return a default value if something is null. This is the syntax:

maybeValue ?: guaranteedValue

If maybeValue is null, then the guaranteedValue is used. If maybeValue isn’t null then ?: used. For example:

var number: Int? = null
var result = number ?: "Number is null"

println(result) // Number is null

Lambdas

Lambdas enable functional programming as it can decrease the code lines on a source file—the current configuration of the lambdas functions with Android. However, Kotlin has “walked the extra mile” as it guarantees that the user does not have to alter the build configuration. There are multiple cases with the Android SDK in which the user applies a single method or sets up a listener, and Lambdas perform quite well in those situations.

{argumentName: argumentType -> // lamda body}

Scope functions

The purpose of scope functions are to provide a block with the context of a given object. There are five of them: letrunwithapply, and also.

let: It can be used to invoke one or more functions on results of call chains.

Without let
val basicSalary = getBasicSalary()
calculateHRA(basicSalary)
calculateDA(basicSalary)
calculateTA(basicSalary)
With let
getBasicSalary().let{
    calculateHRA(it)
    calculateDA(it)
    calculateTA(it)
}

apply: Use it when you accessing multiple properties of an object.

Without apply
val user = User()
user.name = "Simform"
user.email = "simformsolutions@gmail.com"
With apply
val user = User().apply{
    name = "Simform"
    email = "simformsolutions@gmail.com"
}

with: It is also used to call multiple methods on the same object.

Without
calculateHRA(basicSalary)
calculatePF(basicSalary)
Using with
with(basicSalary){
    calculateHRA(this)
    calculatePF(this)
}

run: It is also a scope function and useful when you want to do object initialization and some computation of return value.

val user = User().run{
    name = "Simform"
    formatAddress()
}

also: Use it for actions that need a reference rather to the object than to its properties and functions, or when you don’t want to shadow this reference from an outer scope.

val numbers = mutableListOf("one", "two", "three")
numbers.also { 
    println("The list elements before adding new one:$it") 
}
.add("four")

Data class(POJOs/POCOs):

These data classes distinguish business logic from pure data by clarifying the matter and intent of the model. Using the JSON or Gson parsing libraries with the data classes can help to create a default constructor that carries default values.

Data class provides the following functionalities by default.
1. getters (and setters in case of var s) for all properties
2. equals()
3. hashCode()
4. toString()
5. copy()
6. component1()component2(), …, for all properties (see Data classes)

Companion Object

The singleton objects that carry a class consisting of variables and methods are called companion objects. Any companion object specifies constants and procedures in comparison to Java. Although Kotlin lacks such static methods and variables, it also lacks such concepts. But, Kotlin possesses the “companion objects” concept. Like in Java, companion objects enable methods and defined constants.

The use of static variables and methods in Android are used for activity intents or fragments to the creation of static factories. Companion objects must be used to help maintain static access inside Kotlin.

Extension functions

Extension functions are functions that are defined for specific data types and calling these functions is the same as member functions with the (.) operator. Extension function is used to extend the functionality of a specific class by creating functions that are only called upon that class object and are user-defined. With the extension functions, we can add more functions to the classes that we don’t have access to like built-in classes (Ex. Int, String, ArrayList, etc..). Kotlin has many inbuilt extension functions like toString(), filter(), map(), toInt() etc..

fun Int.returnSquare(): Int { return this * this }
//Calling the extension function
val number = 5
println("Square is ${number.returnSquare()}")   // output: 25

Lateinit 

Kotilin comes with another significant feature – null safety. The “latenit” command initializes an Android-preferable variable, along with a null safety feature. However, after long durations of Java developments, it takes some time to specialize in this characteristic. A field is assigned with a probable declaration of it being null. The lateinit language feature can be troublesome at some point in time. The views will remain inside the Fragment or Activity. However, its declaration has to be developed after the inflation of its layout on the onCreate/onCreateView.

Leveraging Let

Unless the object value is “null”, let offer permission for a block execution. Leveraging Let increases the readability of a code while preventing null checks. The “let” function assigns its user with an un-nullable variable – it to ensure usage continuity against being nulled out.

Coroutines Against Asynctask

The coroutines never cause memory leakage, but rather they help enhance readability. Asynctask can cause leakages and appear cluttered. The RxJava is still required to perform the majority of the async objectives in the system. During this transition, the coroutines need extra reliance with support from the gradle.properties file. The coroutines can help program developers to create asynchronous simple inline codes. However, they can even alter the UI interface directly.

Conclusion

Thanks for reading. I hope you found these tips useful.