How To Use Extensions Method In Kotlin

How To Use Extensions Method In Kotlin
 

Introduction

 
In this article, we will learn how to create and use extensions for Android development using Kotlin. We have read about Kotlin for Android development. If you are new to Kotlin, read my previous article on Kotlin:

Extensions

 
Kotlin, similar to C# and Gosu, provides the ability to extend a class with new functionality without having to inherit from the class or use any type of design pattern such as Decorator. This is done via special declarations called extensions.
 

Coding Part

 
I have detailed the article as in the following steps.
  • Step 1 - Creating a new project with Kotlin
  • Step 2 - Creating Extensions in Kotlin
  • Step 3 - Implementation of Extension in Kotlin
Step 1 - Creating a new project with Kotlin
  1. Open Android Studio and select "Create new project".
  2. Name the project as per your wish and tick the Kotlin Support checkbox.
  3. Then, select your Activity type (For Example - Navigation Drawer Activity, Empty Activity, etc.).

    How To Use Extensions Method In Kotlin

  4. Click the "Finish" button to create a new project in Android Studio.
Step 2 - Creating Extensions in Kotlin
 
In this part, we will see how to create an extension for Kotlin.
  1. To declare an extension function, we need to prefix its name with a receiver type, i.e. the type being extended. The following adds a swap function to MutableList<Int>.
    1. fun MutableList<Int>.swap(index1: Int, index2: Int) {  
    2.     val tmp = this[index1] // 'this' corresponds to the list  
    3.     this[index1] = this[index2]  
    4.     this[index2] = tmp  
    5. }  
  1. We will take an example to show Toast with Short duration. Traditionally, the Toast is shown like below.
    1. Toast.makeText(this, message, Toast.LENGTH_SHORT).show()  
  1. We can simplify this by the using extensions in Kotlin.

  2. Create a Kotlin file named as “Extensions.kt”. Then, add the following code part.
    1. fun Context.showShortToast(message: CharSequence) {  
    2.     Toast.makeText(this, message, Toast.LENGTH_SHORT).show()  
    3. }  
    Here, the base or receiver type of toast is “Context”. So, we have created a function prefixed with “Context”.
  1. In the same way, I have created an extension to show “Toast with Long duration” and “Alert Dialog with the single option”. You can find the full code below.
    1. package com.androidmad.ktextensions  
    2.   
    3. import android.content.Context  
    4. import android.support.v7.app.AlertDialog  
    5. import android.support.v7.app.AppCompatActivity  
    6. import android.view.View  
    7. import android.widget.Toast  
    8.   
    9. fun Context.showShortToast(message: CharSequence) {  
    10.     Toast.makeText(this, message, Toast.LENGTH_SHORT).show()  
    11. }  
    12.   
    13. fun Context.showLongToast(message: CharSequence) {  
    14.     Toast.makeText(this, message, Toast.LENGTH_LONG).show()  
    15. }  
    16.   
    17. fun AppCompatActivity.showAlert(title: CharSequence, message: CharSequence) {  
    18.     val builder = AlertDialog.Builder(this)  
    19.             .setTitle(title)  
    20.             .setMessage(message)  
    21.             .setPositiveButton("Ok", { dialog, which ->  
    22.             })  
    23.   
    24.     val dialog: AlertDialog = builder.create()  
    25.     dialog.show()  
    26. }  
Step 3 - Implementation of Extension in Kotlin
 
In this section, we will see how to call the above-created extension method in Android.
  1. Create a layout file named as “activity_main.xml” and add the following code snippets.
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
    4.     xmlns:tools="http://schemas.android.com/tools"  
    5.     android:layout_width="match_parent"  
    6.     android:layout_height="match_parent"  
    7.     tools:context="com.androidmad.ktextensions.MainActivity"  
    8.     tools:layout_editor_absoluteY="81dp">  
    9.   
    10.     <Button  
    11.         android:id="@+id/btn_short"  
    12.         android:layout_width="wrap_content"  
    13.         android:layout_height="wrap_content"  
    14.         android:layout_marginTop="128dp"  
    15.         android:text="Show Short Toast"  
    16.         app:layout_constraintEnd_toEndOf="parent"  
    17.         app:layout_constraintStart_toStartOf="parent"  
    18.         app:layout_constraintTop_toTopOf="parent" />  
    19.   
    20.     <Button  
    21.         android:id="@+id/btn_long"  
    22.         android:layout_width="wrap_content"  
    23.         android:layout_height="wrap_content"  
    24.         android:layout_marginBottom="208dp"  
    25.         android:text="Show Long Toast"  
    26.         app:layout_constraintBottom_toBottomOf="parent"  
    27.         app:layout_constraintEnd_toEndOf="parent"  
    28.         app:layout_constraintStart_toStartOf="parent" />  
    29.   
    30.     <Button  
    31.         android:id="@+id/btn_alert"  
    32.         android:layout_width="wrap_content"  
    33.         android:layout_height="wrap_content"  
    34.         android:layout_marginBottom="92dp"  
    35.         android:text="Show Alert Dialog"  
    36.         app:layout_constraintBottom_toBottomOf="parent"  
    37.         app:layout_constraintEnd_toEndOf="parent"  
    38.         app:layout_constraintStart_toStartOf="parent" />  
    39.   
    40. </android.support.constraint.ConstraintLayout>  
  1. The output of the layout file looks like below.

    How To Use Extensions Method In Kotlin

  2. We have three buttons in our screen to show Toast with Short duration, Long duration and Alert dialog with single option. Open your MainActivity.kt add click listeners for the buttons.
    1. // Toast with Short Duration  
    2. showShortToast("Show Short Toast using extensions method")  
    3. // Toast with Long Duration  
    4. showLongToast("Show Long Toast using extensions method")  
    5. // Alert Dialog with Single Option  
    6. showAlert("Android Extensions method""Show Alert Dialog")  
  1. Full code of the MainActivity.kt below..
    1. package com.androidmad.ktextensions  
    2.   
    3. import android.support.v7.app.AppCompatActivity  
    4. import android.os.Bundle  
    5. import kotlinx.android.synthetic.main.activity_main.*  
    6.   
    7. class MainActivity : AppCompatActivity() {  
    8.   
    9.     override fun onCreate(savedInstanceState: Bundle?) {  
    10.         super.onCreate(savedInstanceState)  
    11.         setContentView(R.layout.activity_main)  
    12.   
    13.         btn_short.setOnClickListener({  
    14.             showShortToast("Show Short Toast using extensions method")  
    15.         })  
    16.   
    17.         btn_long.setOnClickListener({  
    18.             showLongToast("Show Long Toast using extensions method")  
    19.         })  
    20.   
    21.         btn_alert.setOnClickListener({  
    22.             showAlert("Android Extensions method""Show Alert Dialog")  
    23.         })  
    24.     }  
    25. }  
Reference
Download Code
 
You can download the full source code of the article in GitHub. If you like this article, do star the repo.