Kotlin Invoking Function Types 🎯

beginner
12 min

Kotlin Invoking Function Types 🎯

Welcome to our comprehensive guide on Kotlin Invoking Function Types! In this lesson, we'll delve deep into understanding how to invoke different function types in Kotlin, with practical examples and real-world applications. Let's get started! 📝

Functions as Values 💡

In Kotlin, functions are first-class citizens, which means they can be assigned to variables, passed as arguments to other functions, and returned from other functions.

kotlin
fun greet(name: String) = println("Hello, $name!") // Function declaration fun main() { val greeting = greet // Function assigned to a variable greeting("Alice") // Invoking the function through the variable }

In the above example, we've defined a greet function and assigned it to the greeting variable. Then we invoked the function using the variable.

Function Types 📝

Kotlin has four main function types:

  1. Function 0 (() -> Unit) - No parameters, no return type
  2. Function 1 ((T) -> R or (Parameter) -> ReturnType) - One parameter, one return type
  3. Function 2 ((T1, T2) -> R or (Parameter1, Parameter2) -> ReturnType) - Two parameters, one return type
  4. Function N ((T1, T2, ..., TN) -> R or (Parameter1, Parameter2, ..., ParameterN) -> ReturnType) - N parameters, one return type

Invoking Function Types with Lambdas 💡

We can invoke these function types using Lambdas. Lambdas are anonymous functions that can be used wherever a function type is expected.

kotlin
fun main() { val greetAlice = { println("Hello, Alice!") } // Lambda function greetAlice() // Invoking the Lambda function }

In the above example, we've created a Lambda function to greet Alice.

Function Types with Parameters and Return Types 📝

Let's create a function that calculates the square of a number using a Lambda function:

kotlin
fun square(number: Int, squareIt: (Int) -> Int) = number * number * squareIt(number) fun main() { val squareNumber = square(5) { it * it } // It is a shorthand reference for the parameter println(squareNumber) // Output: 25 }

In the above example, we've defined a square function that takes an Int, multiplies it by itself, and multiplies the result by the result of the provided Lambda function (squareIt).

Quiz 💡

Quick Quiz
Question 1 of 1

What is the return type of the following function type? `(String) -> Unit`

We hope you enjoyed learning about Invoking Function Types in Kotlin! Stay tuned for more engaging and practical lessons. Happy coding! 💡🎉