Kotlin / Kotlin Extensions and Higher-Order Functions

Building Custom Utilities with Extensions

In this tutorial, we will explore how to build custom utilities with extensions in Kotlin. This can help you expand the functionality of existing classes and improve code readabil…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explains how to extend functionality and use higher-order functions in Kotlin.

Building Custom Utilities with Extensions in Kotlin

1. Introduction

In this tutorial, we aim to provide you with a comprehensive guide on how to build custom utilities with extensions in Kotlin. We'll demonstrate how you can extend the functionality of existing classes to create more readable and maintainable code.

By the end of this tutorial, you will learn:
- The basics of extension functions
- How to create and use custom utility functions with extensions in Kotlin

Prerequisites:
- Basic understanding of Kotlin programming language
- Basic knowledge of object-oriented programming concepts

2. Step-by-Step Guide

In Kotlin, extension functions allow you to "add" methods to existing classes without inheriting from them. You can call these methods just like any other regular methods on this class.

Let's start by creating a simple extension function for the String class:

fun String.addExclamation(): String {
    return this + "!"
}

Here, we've created an extension function addExclamation(), that adds an exclamation mark at the end of any string.

3. Code Examples

Let’s dive deeper with more examples.

Example 1:

// Extension function for String class
fun String.addExclamation(): String {
    return this + "!"
}

fun main() {
    val greeting = "Hello World"
    println(greeting.addExclamation())  // Output: Hello World!
}

Explanation: In this code, we have added an extension function addExclamation() to the String class. In the main function, we call this extension function on a String object greeting.

Example 2:

// Extension function for List class
fun List<String>.printList() {
    for (item in this) {
        println(item)
    }
}

fun main() {
    val fruits = listOf("Apple", "Banana", "Cherry")
    fruits.printList()
    // Output: 
    // Apple
    // Banana
    // Cherry
}

Explanation: In this example, we have added an extension function printList() to the List class. This function prints out each item in the list. In the main function, we call this extension function on a List object fruits.

4. Summary

In this tutorial, we've covered how to create and use custom utilities with extensions in Kotlin. You've learned how to extend the functionality of existing classes and how to make your code more readable and maintainable.

For further learning, consider exploring more about Kotlin's other features such as null safety, lambda expressions, and coroutines. You can refer to the official Kotlin documentation for more information.

5. Practice Exercises

Here are some exercises for you to practice:

  1. Create an extension function for the Int class that checks if an integer is even.
  2. Create an extension function for the List class that returns the sum of all integers in the list.

Solutions:

fun Int.isEven(): Boolean {
    return this % 2 == 0
}

Explanation: This function returns true if the integer is divisible by 2, and false otherwise.

fun List<Int>.sumList(): Int {
    var sum = 0
    for (item in this) {
        sum += item
    }
    return sum
}

Explanation: This function iterates over each integer in the list, adds them up, and returns the sum.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Backlink Checker

Analyze and validate backlinks.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help