In Kotlin, you can pass a function as a parameter to another function by using the function type notation. Kotlin supports higher-order functions, which means you can treat functions as first-class citizens and pass them around as arguments.
Here's an example of how to pass a function as a parameter to another function:
// Define a function that takes another function as a parameter
fun executeOperation(operation: () -> Unit) {
// Execute the operation
operation()
}
// Define a function that will be passed as a parameter
fun printMessage() {
println("Hello, world!")
}
// Pass the function 'printMessage' as a parameter to 'executeOperation'
executeOperation(::printMessage)
In the example above, the executeOperation
function takes a function as a parameter. The function type () -> Unit
indicates that the parameter is a function that takes no arguments and returns no value.
The printMessage
function is defined separately, and then we pass it as an argument to executeOperation
using the ::
operator, which is used to create a function reference.
When executeOperation
is called with ::printMessage
as the argument, it executes the function and prints "Hello, world!".
Note that the executeOperation
function can accept any function that matches the function type () -> Unit
. You can pass different functions with different names and implementations as long as they match the required function type.
Comments
Post a Comment