Kotlin has the ability to treat functions as values ​​and store them in variables. There are two basic approaches: assignment using one lambda expression or the use of one Function reference. This is useful when you want to pass functions as arguments to other functions or change them dynamically at runtime.

Assignment using a lambda expression

In another chapter we will deal with the topic of lambdas in great detail. At this point, the basic knowledge about it is enough for us.

Lambda expressions are compact pieces of code that perform specific actions and provide a abbreviated representation of functions. Lambdas are often referred to as lambda functions.

The syntax of lambda expressions in Kotlin is curly braces {}, which enclose the code of the lambda expression, and optionally a list of parameters preceding the arrow -> be specified. Here is an example of the general syntax of a lambda expression:

A concrete example of a lambda expression that adds two numbers looks like this:

In this example, the lambda expression is in the variable add saved. The lambda expects two Intparameters and returns one Int-Value returned. The code inside the curly braces performs the calculation, in this case the addition of a and b. Within the main()-Function becomes the defined Lambda function using the variable name add called and the arguments 3 and 5 are passed to the function.

Function reference in Kotlin

A function reference is a way to reference an already declared function without calling it directly.

In this example we define a function called catfish, which adds two integers, and stores a reference to that function in a variable called addFunction. The double colon operator :: is used to reference the sum function.

One can also dynamically change the value of a variable that contains a function reference. The new value must match the type of the variable. 

Using function references in Kotlin offers a number of benefits that improve code flexibility, modularity, and maintainability.

Leave a Comment

Your e-mail address will not be published. Required fields are marked with * marked