Press enter to see results or esc to cancel.

# Lesson 40: Access to external variables to the lambda expression

##### Share this
()

We have seen in previous concepts that a lambda expression is when we send an anonymous function directly to a higher-order function.
Within the lambda function, we can access the parameters of the same if you have them, define local variables and we will now see that we can access external variables to the defined lambda expression.

Problem 1

Make a higher-order function that receives an array of integers and a function with an Int-type parameter and returns nothing.

The function must send each element of the array to the defined lambda expression.

In the main function, define an array of 10-element integers and store random values between 0 and 99.

Print of the arrangement:

• The quantity of multiples of 3
• The sum of all components greater than 50

Project154 – Principal.kt

``````fun runAll (array: IntArray, fn: (Int) -> Unit) {
for (element in array)
(fn (element))
}
// www.coding180.com
fun main (parameter: Array <String>) {
val array1 = IntArray (10)
for (i in array1.indices)
array1 [i] = ((Math.random () * 100)). toInt ()
println ("Impression of the entire array")
for (element in array1)
print ("\$element")
println()
var amount = 0
runAll (array1) {
if (it% 3 == 0)
amount++
}
println ("The number of multiples of 3 is \$amount")
var sum = 0
runAll (array1) {
if (it> 50)
sum += it
}
println ("The sum of all elements greater than 50 is \$sum")
}``````

The most important thing is to understand and take into account that a variable that we define outside of the expression lambda; we can accede it inside the expression:

```    Var amount = 0
RunAll (array1) {
If (it% 3 == 0)
amount++
}
Println ("The number of multiples of 3 is \$amount")
```

The variable amount is of type Int and it is initialized in 0 before calling the function to runAll and pass the lambda expression where we increase the counter “amount” every time we analyze an element of the array that sends us the higher order function.

When all the executions of the lambda expression are finished we proceed to show the counter.

Similarly to sum all the components of the array that have a value greater than 50 we call the function to runAll and in the lambda expression we accumulate the component as long as it has stored a value greater than 50:

```    Var sum = 0
RunAll (array1) {
If (it> 50)
Sum + = it
}
Println ("The sum of all elements greater than 50 is \$sum")
```

Another thing that should be clear is that, when a function does not return data and is a parameter of another function it is mandatory to indicate the Unit object as data of return:

```Fun runAll(array: IntArray, fn: (Int) -> Unit) {
```

The function runAll also does not return data but Kotlin interprets by default that it returns a type Unit. Then generally the syntax is not used:

```(Int array, int, array,
```

It is not common to indicate the Unit object if the function does not return data, by default Kotlin knows that it must return a Unit object.

The IntArray class like other similar classes ByteArray, ShortArray, FloatArray etc. They have a method called forEach that must be sent a lambda expression, which is executed for each element of the array in a similar way to the function that we create.

Problem 2

Solve the same problem but use the forEach method that the IntArray class has to analyze all the components of the array.

In the main function, define an array of 10-element integers and store random values between 0 and 99.

Print of the arrangement:

• The quantity of multiples of 3
• The sum of all components greater than 50

Project155 – Principal.kt

``````fun main (parameter: Array <String>) {
val array1 = IntArray (10)
for (i in array1.indices)
array1 [i] = ((Math.random () * 100)). toInt ()
println ("Impression of the entire array")
for (element in array1)
print ("\$element")
println ()
var amount = 0
array1.forEach {
if (it% 3 == 0)
amount ++
}
// www.coding180.com
println ("The number of multiples of 3 is \$amount")
var sum = 0
array1.forEach {
if (it> 50)
sum += it
}
println ("The sum of all elements greater than 50 is \$sum")
}``````

It is more logical to use the higher-order forEach function provided by the IntArray class instead of creating our own function (we did this in the above problem in order to practice creating higher-order functions)

To count the number of multiples of 3 we define a counter before calling forEach:

```    Var amount = 0
Fix1.forEach {
If (it% 3 == 0)
amount++
}
Println ("The number of multiples of 3 is \$amount")
```

Remember that inside the lambda expression we have access to the external variable quantity.

Problem 3

Declare a Person class with the properties; name and age, define its methods as impression and another that returns true if it is of age or false otherwise (18 years or more to be greater)
In the main function define an array with four elements Of type Person. Calculate how many people are of age by calling the forEach method of the Array class.

Project156 – Principal.kt

``````class Person (val name: String, val age: Int) {
fun print () {
println ("Name: \$name Age: \$age")
}

fun isMajor () = if (age >= 18) true else false
}
// www.coding180.com
fun main (parameter: Array <String>) {
val people: Array <Person> = arrayOf (Person ("ana", 22),
Person ("john", 13),
Person ("carlos", 6),
Person ("maria", 72))
println ("List of people")
for (per in people)
per.print ()
var cont = 0
people.forEach {
if (it.isMajor ())
Cont
}
println ("Number of people of age: \$cont")
}``````

The Array class also has a forEach method that passes a lambda expression to it and receives as a parameter, an Array element each time it is executed. By means of the parameter, it in this case is of the Person class we analyze if it is of age:

```    Var cont = 0
people.forEach {
If (it.isMajor ())
Cont
}
Println ("Number of people of age: \$cont")
```

Always remember that we use the word it to make our program more concise, in the long form we can write:

```    Var cont = 0
people.forEach {person: Person ->
If (person.isMajor ())
Cont
}
Println ("Number of people of age: \$cant")
```

Proposed problem

• Declare a class Given its property value and two methods that allow you to roll the die and print its value.
In the main define an Array with 5 objects of type Dice.
Pull the 5 dice and print out how many 1, 2, 3, 4, 5 and 6 came out.
```Solution

[sociallocker id="958"]```
``````class Given (var value: Int = 1) {

fun throww () {
value = ((Math.random () * 6) + 1) .toInt ()
}

fun print () {
println ("Value of data: \$value")
}
}
// www.coding180.com
fun main (parameter: Array <String>) {
var Dice: Array <Given> = arrayOf (Given (), Given (), Given (), Given (), Given ())
for (given in Dice)
given.throww()
for (given in Dice)
given.print ()

var cont1 = 0
var cont2 = 0
var cont3 = 0
var cont4 = 0
var cont5 = 0
var cont6 = 0

Dice.forEach {
when (it.value) {
1 -> cont1 ++
2 -> cont2 ++
3 -> cont3 ++
4 -> cont4 ++
5 -> cont5 ++
6 -> cont6 ++
}
}
println ("Amount of data having the value 1: \$cont1")
println ("Number of dice having the value 2: \$cont2")
println ("Number of dice that have the value 3: \$cont3")
println ("Number of dice having the value 4: \$cont4")
println ("Number of dice having the value 5: \$cont5")
println ("Number of dice having the value 6: \$cont6")
}``````
`[/sociallocker]`

How useful was this Lesson?

Click on a star to rate it!

Average rating / 5. Vote count:

Be the first to rate this post.!

As you found this post useful...

Follow us on social media!

We are sorry that this lesson was not useful for you!

Let us improve this lesson!

Tell us how we can improve this lesson?