Android Kotlin

Android Kotlin

Spread the love

Introduction

Kotlin is a general-purpose, open-source, cross-platform programming language. The language was designed and developed by JetBrains. The first stable version of Kotlin v1.0 release on 15 February 2016. In May 2019, Google is adding Kotlin as an official programming language for the Android application development. Kotlin boost developer productivity and increase developer happiness. After Google added Kotlin into the official language, Kotlin widely using for Android Application development. Compare to Java, Kotlin reduces the number of lines in the program.

 Major Advantages of Kotlin.

  • Null safe: Kotlin has inbuilt null safety
  • Interoperable: Interoperability is Kotlin’s core purpose. Kotlin is 100% interoperable with Java, so the developer can have as little or as much of Kotlin in your project as you want.
  • Structured Concurrency: Kotlin’s coroutines make asynchronous code as easy to work with as blocking code. Coroutines dramatically simplify background task management for everything from network calls to accessing local data.
  • Expressive and concise: You can do more with less. Express your ideas and reduce the amount of boilerplate code.
  • Extension methods: Extend a class with new functionality without having to inherit from the class or use design patterns such as Decorator.

Extension Methods in Kotlin:

With the help of Extension, the developer can extend a class with new functionality without having to inherit from the class or use design patterns such as Decorator.

Extension functions have the potential to make your code more brief, readable, and logical by removing boilerplate code from your project. Besides, less code means more opportunities for not making high errors.

Advantages of using Extension:

  • With the help of Extension, the developer can add new functionality to a final class. 
  • With the help of Extension, the developer can add new functionality without sub-classing, which means the object reference and its implementation can be mentioned in your base class. 

When a new function is added to an existing class it is known as Extension Function and this function is used as a regular function inside that class.

To declare an extension function, the developer needs to add receiver type as the prefix to its name, i.e. the class name or the type being extended.

fun <className>.<methodName>() 

In the above declaration syntax, <className> is a receiver type and the <methodName>() is an extension function.

Kotlin extension function example:

For instance, suppose that we want to call a method perimeter () of Circle class which isn’t defined in a class. This indication Circle.perimeter() function is understood as an extension function, and Circle class is known as receiver type as well.

class Circle (val radius: Double){ 

    /* member function*/

    fun area(): Double{ 

        return Math.PI * radius * radius; 

    } 

fun main(){ 

    /* Extension function */

    fun Circle.perimeter(): Double{ 

        return 2*Math.PI*radius; 

    } 

    val newCircle = Circle(2.5); 

    /* Call member function */

    println(“Area is : ${newCircle.area()}”) 

    /*Call extension function */

    println(“Perimeter is : ${newCircle.perimeter()}”) 

}

Extended Library Classes

With the help of Extension in Kotlin, a developer can extend the library classes as well as user-defined classes without modifying the library

fun main(){ 

    // Extension function defined for Int 

    fun Int.abs() : Int{ 

        return if(this < 0) -this else this

    } 

   println((-10).abs()) 

    println(10.abs()) 

}

Nullable Receiver

The extensions function can be defined with a nullable receiver type.

Nullable extensions can be called on an object variable even if its value is null.

In this situation, null checking (this == null) is performed inside the body.

By using this, it allow you to call toString() in Kotlin without checking for null.

fun Any?.toString(): String {

    if (this == null) return “null”

    return toString()

}

Companion object extensions:

If a companion object is defined inside a class, then the developer can also define extension functions and properties for that companion object.
Example of companion object:

class MyClass {  

    companion object {  

        fun create():String{  

            return “create method of companion object”  

        }  

    }  

}  

fun main(args: Array<String>){  

val instance = MyClass.create()  

}  

Example of companion object extension:

class SampleClass {

   companion object{  

      fun create(): String{  

            return “create method of companion object”  

        }  

    }

}

fun SampleClass.Companion.printCompanion() { println(“companion object extension”) }

fun main() {

    SampleClass.printCompanion()

}

Scope of extensions

Commonly all developers define extensions on the top level – directly under packages.

package org.innovature.declarations 

fun List<String>.getLongestString() { /*.code.*/}

If an extension needs outside of the declaration package, the developer needs to import it at the call site.

package org.innovature.usage

import org.innovature.declarations.getLongestString

fun main() {

    val list = listOf(“yellow”, “white”, “blue”)

    list.getLongestString()

}

Conclusion

Without implementing the inheritance or using a design pattern, the developer can easily extend a class with new functionality with the help of Kotlin Extension. This will be helpful for becoming your code more brief, readable, and logical by removing boilerplate code from your project.

For more information on the topic go to Innovature’s Kotlin page.

Jithin MK

Experienced Engineer of Innovature's with a significant background of working in the Information Technology and services industry. Collaborative team player to provide a rapid, robust and client-acclaimed user experience on the solutions.

54321
(1 vote. Average 5 of 5)
Leave a reply

Your email address will not be published. Required fields are marked *