Kotlin Best Practices for Android Developers — Part 1

The recommended best practices for Kotlin-Android developers.

Photo by Louis Tsai on Unsplash

As you begin Android development using Kotlin, remember to follow Kotlin’s best practices.

These practices will help you utilize Kotlin’s powerful language features effectively. This, in turn, will enhance your code’s quality and maintainability.

If you are not a medium member you can read this story here

Null safety — Keep the code safe

Kotlin has nullable and non-nullable types of variables. IDE itself enforces you to use it properly and write the program in a null safety manner.

// Non nullale type
var name: String = "Tony"
name = null // compilation error

// Nullale type
var name: String? = "Tony"
name = null

On a nullable type > only Safe(?.) or Non-nullable operator(!!.) are allowed.

var name: String? = "Tony"
println(name.length) // since name is nullable, it will show compile time error

var name: String? = "Tony"
println(name?.length) // Safe call

// WHAT IF name is NULL
var name: String? = null
println(name?.length) // prints null - entire expression becomes null

// Non-nullable operator(!!.)
var name: String? = null
println(name!!.length) // Throws nullpointer exception

Use the ?: Elvis operator to give a default value.

var name: String? = "Tony"
var length = name?.length ?: 0

When to use mutable vs immutable collections?

  • Mutable collections are faster in performance compared to immutable collections.
  • For local variables where synchronization and encapsulation are rarely needed — Use mutable collections.
  • Immutable collections are used when safety is required.
val mutableList = mutableListOf("apple", "banana", "orange")
val mutableSet = mutableSetOf("apple", "banana", "orange")
val mutableMap = mutableMapOf("apple" to 1, "banana" to 2, "orange" to 3)
val arrayList = ArrayList<Int>()

val immutableList = listOf("apple", "banana", "orange")
val immutableSet = setOf("apple", "banana", "orange")
val immutableMap = mapOf("apple" to 1, "banana" to 2, "orange" to 3)

More than one “If-statement”? refactor it into a “When”

a ‘when’ statement gives improved readability and maintainability.

when(expression) {
 value1 -> statement1
 value2 -> statement2
 default -> defaultStatement

Constructors best practices

Kotlin provides a cool feature “Named & Default Arguments” which is a better option compared to the below patterns.

  • Telescoping constructor pattern.

Series of constructors, each with a different number of parameters, where each constructor calls another constructor with more parameters.

  • Builder pattern.

In Java, a builder pattern is used when the object has a complex set of parameters and to get the flexibility to name parameters, specify parameters in any order, and have default values.

Both these requirements are simply served by the “Named & Default Arguments” in Kotlin.

class Person(
    val name: String = "Tony Stark",  // Default value for name parameter
    val age: Int = 45               // Default value for age parameter

fun main() {
    // Creating a Person object without specifying arguments
    val person1 = Person()
    println("Name: ${person1.name}, Age: ${person1.age}")

    // Creating a Person object with specified arguments
    val person2 = Person("David", 25)
    println("Name: ${person2.name}, Age: ${person2.age}")

Tip: Try to use a primary constructor and, if necessary, an init block since Named and default arguments give flexibility and can avoid unnecessary secondary constructors.

Stay tuned and subscribe for more Articles on Android and Kotlin.

If you enjoyed this article, consider trying out the AI service I recommend. It provides the same performance and functions to ChatGPT Plus(GPT-4) but more cost-effective, at just $6/month (Special offer for $1/month). Click here to try ZAI.chat.

Best Practices
Recommended from ReadMedium