Skip to content

7 Quick Kotlin Tips for Android Developers

    Write code in Kotlinic ways and improve your Android skills.

    Kotlin was introduced to make Android development a whole lot easier and faster. After being named an official language for Android, it has slowly taken over Java and is the first choice for Android developers today.

    For Java developers switching to Kotlin, the transition couldn’t have been easier, owing to their similarities. But at the same time, it’s really easy to ignore the uniqueness or rather idiomatic aspects of Kotlin. This can lead to writing code similar to Java.

    Gladly, we can leverage some of the Kotlinic (a term inspired by Pythonic) ways of writing less verbose code in Android. Let’s get started.

    Use ‘let’ Function for Checking Nullable Properties

    It’s fairly common to use the “if not null” control structure for doing a null check on types before proceeding. Using Kotlin’s let extension function helps avoid the complex branching logic.

    Kotlin’s let is a scoping function such that properties declared within it cannot be used outside. One can use this for nested lets or for chaining a bunch of nullable. Here’s an example:

    val a: Int? = null
    if (a != null) {
        doSomething(a)
    }//less code
    a?.let { doSomething(it) }

    Using Kotlin’s Elvis operator(?:) helps provide default values for nullable properties. For instance, in the above code, you can call the function as doSomething(a ?: 0) — thereby ensuring a has a default value.

    Generate Kotlin Lists With a Single Line of Code

    If you’re looking to create a list with default values, it’s fairly straightforward. The below line of code creates an integer array of length 10 with each element initialized as 1.

    While this was quick and easy, one might wonder how to create a list with different elements. Of course, the classical way of doing this is with for loops. But by leveraging the power of Kotlin, you can do it in a single line.

    val list = arrayListOf<Int>()
    for (x in O until 10 step 2){
    list.add (x)
    }
    //in a single line
    val newList = List(5, {it*2})
    //prints: [0,2,4,6,8]

    Use ‘require’ or ‘check’ Functions for Early Exit Conditions

    The require function validates the argument passed and throws an IllegalArgumentException if it’s false.

    The check function, on the other hand, throws IllegalStateException when the object state is false.

    Both of these are handy when setting early exit conditions in your Kotlin codebases in Android.

    if (n < 0) {
       throw IllegalArgumentException("message")
    }//use this instead
    require(n >= 0) { "Number must no be negative" }
    //check function throws IllegalStateException
    checkNotNull(arg){
    "message"
    }

    Use the ‘apply’ and ‘with’ Functions to Reduce Boilerplate Code

    Apply and with are two important scoped functions that help eliminate explicit references on an object when setting object properties. In a way both of the functions let you transform an object before returning it.

    The apply function is called on the object initialization, while the with function requires passing the object as an argument.

    By leveraging them, we can reduce some boilerplate code and make our codebases clear and concise.

    //Classic way
    val textView = TextView(this)
    textView.visibility = View.VISIBLE
    textView.text = "sample"
    
    //Kotlinic way using apply
    val textView = TextView(this).apply {
        visiblity = View.VISIBLE
        text = "sample"
    }
    
    //Kotlinic way using with
    val textView = TextView(this)
    with(textView){
      text = "Sample"
      setOnClickListener { print( "You pressed: $text") }
    }

    partition lets you split a list into a pair of sublists where the first one contains elements that meet the condition specified and the remaining are put inside the second sublist.

    groupBy, on the other hand, returns a map of sublists in the form of key-value pairs. By invoking the values property on groupBy, you get a list of lists. The following example demonstrates a use case of each.

    val someList = listof(0, "a", 1, "b", 2, "c");
    val (ints: List<Any>, strings: List<Any>) = 
    someList.partition { (it is Int) }
    
    //ints = [0,1,2]
    //strings = [a,b, c]
    
    val subLists = someList.groupBy { (it is Int) }.values
    //[[0, 1, 2], [a, b, c]]

    Swapping two variables is among the first programming questions developers face. Traditionally, you’d define a temporary variable to interchange the properties. While there is a way to eliminate that and reduce the code to two lines, using a = a-b and b = b-a, we can make it even better.

    By using Kotlin’s idiomatic expression, swapping two properties can be done in a single line, as shown below:

    a = b.also { b = a }

    SOURCE : https://betterprogramming.pub/7-quick-kotlin-tips-for-android-developers-884d1021ab1d