Kotlin. Anonymous functions. Lambda expressions

Anonymous functions. Lambda expressions. Functional type. Examples


Contents


Search other resources:

1. The concept of an anonymous function or lambda expression. Anonymous function declaration

In the Kotlin language, functions can be declared:

  • with function name specification. Such functions are called named functions. More details about the specifics of using named functions are discussed here;
  • without specifying the function name. Functions that do not contain a name in their declaration are called anonymous functions. Anonymous functions are also called lambda expressions.

Compared to named functions, anonymous functions (lambda expressions) interact with code in a different way. These functions bring their own specifics to the code processing performed by the standard functions.

Anonymous functions are useful in the following cases:

  • using a function as an argument when calling another function;
  • return of a function from another function.

If a lambda expression expects to receive a list of parameters, then the general form of its declaration is as follows:

{ params -> expression }

here

  • params – one or more parameters separated by commas. Also, parameters may be missing;
  • expression – an expression that defines the use of params parameters to get the result.

If the lambda expression does not take parameters, then it has the following declaration

{ -> expression }

The main advantage of using lambda expressions (anonymous functions) is the compactness of the program code. The function is not declared once again. The code block of the function is passed specifically as an argument. Thus, code redundancy is avoided.

 

2. Functional type. Function type declaration

The Kotlin language allows you to declare the type of anonymous functions or lambda expressions. Such a type is called a function type. The functional type allows you to extend the use of lambda expressions.

The function type defines the characteristic features of the lambda expression, namely:

  • number of input parameters of the function;
  • types of function parameters;
  • the type of the returned result.

If a function type is defined in the program, then a variable of this type is declared. A variable of a function type can be passed to the code like a regular variable.

The general form of declaring a variable of a function type is as follows:

val lambdaExpr = { params -> expression }

here

  • lambdaExpr – the name of the variable that defines the lambda expression.

 

3. Examples of using anonymous functions (lambda expressions)
3.1. Determine the number of occurrences of a number in an array

The example determines the number of occurrences of the numbers 5 and 8 in a given array of integers.

fun main(args:Array<String>) {

  // 1. Create an array of integers
  var AI : Array<Int> = arrayOf(2, 3, 2, 5, 5, 8, 5, 2, 3, 4, 7);

  // 2. Create a lambda expression that takes an integer 
  //   and returns true if that number is 5. 
  //   Otherwise, the lambda expression returns false.
  val isNumber = { num:Int -> num == 5 }

  // 3. Calculate the number of numbers 5, pass a lambda expression to the count() function
  val n5 = AI.count(isNumber) // n = 3
  println("n5 = " + n5)

  // 4. Calculate the number of numbers 8, the lambda expression is passed 
  //   directly without creating a reference to it
  val n8 = AI.count({ num:Int -> num==8 })
  println("n8 = " + n8)
}

Program result

n5 = 3
n8 = 1

 

3.2. Lambda expression returning the number 50

 

fun main(args:Array<String>) {
  // Lambda expression that returns the number 50
  val num50 = { -> 50 }

  // Calling a lambda expression
  var x = num50()

  // Display the result
  println("x = " + x)
}

Program result

x = 50

 

3.3. Determine the number of occurrences of a given character in a string

The example determines the number of occurrences of the characters ‘o’ and ‘l’ in the string s.

fun main(args:Array<String>) {

  // 1. Some string is given
  var s : String
  s = "Hello, world!"

  // 2. Declare a lambda expression that returns true    //   if the character is equal to the letter 'o'
  val isCharacter = { c : Char -> c == 'o'}

  // 3. Use lambda expression isCharacter to count the number of 'o' characters in string s
  var count = s.count(isCharacter)
  println("count = " + count);

  // 4. Use built-in lambda expression to determine number of 'l' characters in string s
  count = s.count({c:Char -> c == 'l'})
  println("count = " + count)
}

 

3.4. Lambda expression that calculates the sum of two numbers

 

fun main(args:Array<String>) {
  // The sum of two numbers
  val sum={ a:Double, b:Double -> a*b }

  // Calling a lambda expression
  println("sum = " + sum(5.0,8.0))
}

Program result

sum = 40.0

 

3.5. Determine if the given array has at least one element greater than 5. The any() function

Using the any() function in combination with a lambda expression allows you to determine if at least one element of an array matches a given condition.

 

fun main(args:Array<String>) {
  // Some array is given
  var A : Array<Int> = arrayOf(2, 3, 7, 10, -4, -11)

  // Does the array have at least one element greater than 5    
  val ItemMoreThan5 = { item : Int -> item>5 }

  // Function any()
  var n = A.any(ItemMoreThan5)
  println("(>5) = " + n) // true
}

Program result

(>5) = true

 

3.6. Determine if all elements in an array are non-zero. The all() function

Using the combination of the all() function and the corresponding lambda expression, you can determine whether all elements of an array (collection) meet a given condition.

 

fun main(args:Array<String>) {
  // Given an array
  var A : Array<Int> = arrayOf(2, 3, 7, 10, -4, -11)
  var n : Boolean

  // Determine if all elements in an array are non-zero
  val IsNonZero = { item : Int -> item != 0}
  n = A.all(IsNonZero) // true
  println("(!=0) = " + n)
}

Program result

(!=0) = true

 

3.7. Get a new array in which all elements are greater than 5. The filter() function

In the example, based on the array A of integers, a new list is formed in which all elements are greater than the number 5.

 

fun main(args:Array<String>) {
  // Original array
  var A : Array<Int> = arrayOf(2, 3, 7, 10, -4, -11)

  // Get a new list in which all elements are greater than 5,
  // function filter()
  var B: List<Int> = A.filter({ item:Int -> item > 5}) // B = [ 7, 10 ]

  println("B = " + B)
}

Program result

B = [7, 10]

 

3.8. Calculate the sum of squares of array elements. The sum() function

The calculation of sums of arrays (lists, collections) according to a formula can be done using a combination of the sum() function and a lambda expression.

fun main(args:Array<String>) {
  // Original array
  var A : Array<Int> = arrayOf(2, 3, 7, 10, -4, -11)

  // Calculate the sum of squares of the elements of array A
  var s = A.sumBy { item : Int -> (item*item) } // s = 299
  println("s = " + s)
}

Program result

s = 299

 

3.9. Calculate the sum of array elements that are less than a given value. Combination of filter() and sum() functions

 

fun main(args:Array<String>) {
  // Original array
  var A : Array<Int> = arrayOf(2, 3, 7, 10, -4, -11)
  var s : Int

  // Sum of array elements that are less than 0
  s = A.filter( { item : Int -> item < 0}).sum()
  println("summ (<0) = " + s)
}

Program result

summ (<0) = -15

 


Related topics