How to Pass A Parameter to A Extension Function In Kotlin?

9 minutes read

In Kotlin, you can pass parameters to an extension function just like you would pass parameters to a regular function. When declaring the extension function, simply include the parameter(s) in the parentheses after the function name.


For example, if you have an extension function called "printFormatted" for the String class that takes a delimiter parameter, you can define it like this:


fun String.printFormatted(delimiter: String) { val parts = this.split(" ") println(parts.joinToString(delimiter)) }


When calling the extension function on a string, you can pass the delimiter parameter as follows:


val sentence = "Hello world" sentence.printFormatted("-") // Output: Hello-world


By including the parameter in the extension function definition, you can pass arguments to the extension function just like any other function in Kotlin.

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
Java to Kotlin: A Refactoring Guidebook

Rating is 4.8 out of 5

Java to Kotlin: A Refactoring Guidebook

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

Rating is 4.7 out of 5

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

5
Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

Rating is 4.6 out of 5

Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

6
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.5 out of 5

Kotlin Cookbook: A Problem-Focused Approach

7
Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

Rating is 4.4 out of 5

Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

8
Kotlin and Android Development featuring Jetpack: Build Better, Safer Android Apps

Rating is 4.3 out of 5

Kotlin and Android Development featuring Jetpack: Build Better, Safer Android Apps


How to define an extension function in Kotlin?

An extension function in Kotlin allows you to add new functions to existing classes without inheriting from them or modifying their source code.


To define an extension function in Kotlin, use the following syntax:

1
2
3
fun ClassName.extensionFunctionName(param1: Type, param2: Type): ReturnType {
    // Function body
}


In this syntax:

  • fun is the keyword used to define a function.
  • ClassName is the name of the class to which you want to add the extension function.
  • extensionFunctionName is the name of the extension function you're defining.
  • param1, param2, etc. are the parameters of the extension function, along with their types.
  • ReturnType is the return type of the extension function.
  • The function body contains the logic of the extension function.


Here's an example of defining an extension function for the String class that returns a string in reverse order:

1
2
3
fun String.reverse(): String {
    return this.reversed()
}


You can call this extension function on any String object as if it were a member function:

1
2
3
4
val hello = "hello"
val reversedHello = hello.reverse()

println(reversedHello) // Output: olleh



What is the syntax for defining a higher-order function in an extension function in Kotlin?

A higher-order function is a function that takes another function as a parameter or returns a function.


In Kotlin, you can define a higher-order function within an extension function like this:

1
2
3
4
5
6
7
8
9
fun String.customExtensionFunction(action: (String) -> Unit) {
    action(this)
}

fun main() {
    "Hello, World!".customExtensionFunction { str ->
        println(str)
    }
}


In this example, the customExtensionFunction function is an extension function for String. It takes a function as a parameter that takes a String as an argument and returns nothing. Inside the function body, we simply invoke the passed function with this (the current String instance).


When invoking the customExtensionFunction function in the main function, we pass a lambda function that prints out the String passed to it.


How to overload an extension function in Kotlin?

To overload an extension function in Kotlin, you can simply define multiple extension functions with the same name but different parameter types or number of parameters.


For example, let's say you have an extension function named printInfo for the String class:

1
2
3
fun String.printInfo() {
    println("Printing info for $this")
}


Now, if you want to overload this function with another version that takes an additional parameter, you can define another extension function with the same name but different parameters:

1
2
3
fun String.printInfo(info: String) {
    println("Printing info for $this: $info")
}


You can now call the appropriate version of the printInfo function based on the parameters you provide:

1
2
3
val myString = "Hello"
myString.printInfo() // prints "Printing info for Hello"
myString.printInfo("World") // prints "Printing info for Hello: World"



How to pass a parameter to an extension function in Kotlin?

To pass a parameter to an extension function in Kotlin, you simply declare the parameter within the parentheses of the extension function. Here is an example of how to pass a parameter to an extension function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// Define a class or type that you want to extend
class MyClass {
    // Define a regular function inside the class
    fun regularFunction() {
        // Function implementation
    }
}

// Define an extension function that takes a parameter
fun MyClass.extensionFunction(parameter: Int) {
    // Function implementation that uses the parameter
}

// Usage of the extension function
val myObject = MyClass()
myObject.extensionFunction(10) // Passing the parameter to the extension function


In this example, the extension function extensionFunction is defined for the MyClass type and it takes a parameter of type Int. When calling the extension function on an instance of MyClass, you pass the parameter within the parentheses just like you would with a regular function.


How to access properties of a parameter in an extension function in Kotlin?

In Kotlin, you can access properties of a parameter in an extension function by using the parameter name followed by a dot (.) notation. Here is an example:

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

fun Person.isAdult(): Boolean {
    return age >= 18
}

fun main() {
    val person = Person("Alice", 25)
    
    println(person.isAdult()) // Output: true
}


In the example above, the isAdult() extension function is defined for the Person class, and it accesses the age property of the Person instance using the age parameter inside the function. When we call person.isAdult() in the main() function, it returns true because the age of the person is 25, which is greater than or equal to 18.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To get the raw file extension from the header in Kotlin, you can use a combination of string manipulation and regular expressions. First, you need to extract the content type from the header, which typically contains the file extension. Then, you can use a reg...
In Kotlin, you can pass boolean operators as parameters by using functional interfaces. You can define a functional interface that takes two boolean parameters and returns a boolean result. Then, you can pass the boolean operator as a lambda expression when ca...
In Erlang, you can get the extension from a string filename using the following steps:Start by importing the file library module with the following line of code: -include_lib("kernel/include/file.hrl"). Define a function that takes a filename as a stri...