How to Create And Call an Extension Function In Kotlin?

9 minutes read

To create and call an extension function in Kotlin, follow the steps below:

  1. Create a new Kotlin file or open an existing one.
  2. Define the extension function outside of any class, using the fun keyword followed by the function name. Prefix the defining type with the class or interface that the function extends. For example, if you want to create an extension function for the String class, you would write fun String.myExtensionFunction().
  3. Specify the function body by adding curly braces {} after the function signature.
  4. Inside the function body, you can use the this keyword to refer to the object on which the function is being called. This object will have access to all the properties and functions of the extended class.
  5. Once the extension function is defined, you can call it on any object that belongs to the extended class, as if it were a regular member function. The extension function will appear in the IDE's suggestions and can be called using the regular function call syntax.


Here's an example illustrating the creation and usage of an extension function that capitalizes the first letter of a string:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Extension function
fun String.capitalizeFirstLetter(): String {
    if (isEmpty()) return this
    return this.substring(0, 1).toUpperCase() + this.substring(1)
}

// Usage
fun main() {
    val input = "hello, world!"
    val capitalized = input.capitalizeFirstLetter()

    println(capitalized) // Output: Hello, world!
}


In this example, the extension function capitalizeFirstLetter() is added to the String class. It takes a string, checks if it's empty, capitalizes the first letter (if not empty), and returns the modified string. Finally, the extension function is called on a string object named input, and the output is printed to the console.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin in Action

Rating is 4.9 out of 5

Kotlin in Action

3
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.8 out of 5

Head First Kotlin: A Brain-Friendly Guide

4
Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

Rating is 4.7 out of 5

Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

5
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.6 out of 5

Kotlin Cookbook: A Problem-Focused Approach

6
Java to Kotlin: A Refactoring Guidebook

Rating is 4.5 out of 5

Java to Kotlin: A Refactoring Guidebook

7
Programming Kotlin: Create Elegant, Expressive, and Performant JVM and Android Applications

Rating is 4.4 out of 5

Programming Kotlin: Create Elegant, Expressive, and Performant JVM and Android Applications

8
Advanced Kotlin (Kotlin for Developers Book 4)

Rating is 4.3 out of 5

Advanced Kotlin (Kotlin for Developers Book 4)


What is the scope of an extension function in Kotlin?

The scope of an extension function in Kotlin is limited to the class it is defined in. It cannot access private members or properties of the class, and it cannot be overridden by subclasses. The extension function can be called on instances of the class just like any other member function. Additionally, the extension function can be accessed within the class it is defined in using the this keyword.


How to group multiple extension functions in a single file in Kotlin?

To group multiple extension functions in a single file in Kotlin, follow these steps:

  1. Create a Kotlin file and give it a relevant name. For example, if the extension functions are related to string manipulation, you could name the file StringExtensions.kt.
  2. Define the extension functions in the file. Each extension function should be defined using the fun keyword followed by the receiver type it extends and the name of the function. Inside the extension function, you can access the receiver object using this.


Here's an example of a StringExtensions.kt file with two extension functions:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// StringExtensions.kt

fun String.isPalindrome(): Boolean {
    val reversed = this.reversed()
    return this == reversed
}

fun String.capitalizeWords(): String {
    return this.split(" ").joinToString(" ") { it.capitalize() }
}


In this example, the isPalindrome() function extends the String type and checks whether the string is a palindrome. The capitalizeWords() function extends the String type and capitalizes the first letter of each word in the string.

  1. Now you can use these extension functions by importing the file where you defined them. Since Kotlin automatically imports files based on the file name, you don't need any additional imports. Simply use the extension functions directly on string objects:
1
2
3
4
5
6
7
fun main() {
    val name = "kayak"
    println(name.isPalindrome()) // Output: true

    val sentence = "hello world"
    println(sentence.capitalizeWords()) // Output: Hello World
}


By following these steps, you can group multiple extension functions in a single file and easily reuse them throughout your application.


How to create an extension function that modifies the receiver object in Kotlin?

To create an extension function that modifies the receiver object, you can define the extension function with the receiver object as a parameter and modify its properties or call its methods within the function. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Person(var name: String, var age: Int)

fun Person.greet() {
    name = "Hello, $name!"
}

fun main() {
    val person = Person("John", 25)
    person.greet()

    println(person.name) // Output: Hello, John!
    println(person.age) // Output: 25
}


In this example, we define an extension function greet() for the Person class. This function modifies the name property of the receiver object by appending "Hello, " before the original name. The greet() function is called on a Person object, so it modifies the name property of that object.


When we invoke the greet() function on the person object, it modifies the name property to "Hello, John!". We can then access the modified name property using person.name and it will print "Hello, John!".


How to specify the receiver type in an extension function?

To specify the receiver type in an extension function, you need to define the receiver type before the function name. Here's the syntax:

1
2
3
fun ReceiverType.functionName() {
    // Extension function implementation
}


Here, ReceiverType is the type of the object for which you want to create an extension function. You can then use the this keyword inside the function body to refer to the object on which the extension function is called.


For example, if you want to create an extension function on the String class that prints the length of the string, you can do it like this:

1
2
3
fun String.printLength() {
    println("Length of the string is ${this.length}")
}


Now, you can call this extension function on any string object:

1
2
val str = "Hello, World!"
str.printLength() // Output: Length of the string is 13


In the example above, String is the receiver type, and printLength is the extension function on that type.

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

Kotlin reflection allows you to inspect and manipulate code at runtime. Although Kotlin is fully compatible with Java, accessing Kotlin's reflection API from Java requires some extra steps.To use Kotlin reflection in Java, you need to follow these steps:Im...
To use the pg_cron extension for scheduled tasks in PostgreSQL, you need to follow these steps:Install the pg_cron extension: Download the extension from the PostgreSQL website or use a package manager to install it. On Linux, you can run make && sudo ...
The Kotlin Standard Library functions are a set of utility functions that come built-in with the Kotlin programming language. These functions provide convenient ways to perform common tasks when working with different types of data.To use the Kotlin Standard L...