## Lesson 21 – Functions: internal or local in Kotlin language

Kotlin supports local or internal functions, ie a function within another function.

**Problem 1**

Make a function that allows entering 10 values per keyboard and count how many are multiples of 2 and how many are multiples of 5.

Topic: Functions: internal or local in Kotlin language

**Project96 – Main.kt**

```
fun multiples2y5 () {
fun multiple (number: Int, value: Int) = number% value == 0
// coding180.com
var mult2 = 0
var mult5 = 0
for (i in 1..10) {
print ("Enter value:")
val value = readLine () !!. toInt ()
if (multiple (value, 2))
mult2 ++
if (multiple(value, 5))
mult5++
}
println ("Amount of multiples of 2: $mult2")
println ("Amount of multiples of 5: $mult5")
}
fun main (parameter: Array <String>) {
multiples2y5 ()
}
```

In this problem, we have defined a function called multiples2y5 that aims to load 10 integers per keyboard and verify how many are multiples of 2 and how many multiples of 5.

Topic: Functions: internal or local in Kotlin language

To verify if a number is multiple of another we define a local function called “multiple”, it returns true if the remainder of dividing the first parameter with respect to the second is zero (Eg 10% 2 == 0 returns true since the Remainder of dividing 10 with respect to 2 is 0)

To an internal function, we can only call it from the same function where it is defined, ie the multiple function can only be called inside the multiples2y5 function. If we try to call the multiple function from the main function, a compile-time error is generated.

Topic: Functions: internal or local in Kotlin language

**Proposed problem**

- Make a function that allows loading two integers and shows us the largest of them. Perform this activity with 5 pairs of values.

Implement an internal function that returns the greater of two integers.

**Solution**

Project97

```
fun showMayor () {
fun major (x1: Int, x2: Int) = if (x1> x2) x1 else x2
// coding180.com
for (i in 1..5) {
print ("Enter first value:")
val value1 = readLine () !!. toInt ()
print ("Enter second value:")
val value2 = readLine () !!. toInt ()
println ("The greater of $value1 and $value2 is ${major (value1, value2)}")
}
}
fun main (parameter: Array <String>) {
showMayor ()
}
```

Topic: Functions: internal or local in Kotlin language

## How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

## We are sorry that this post was not useful for you!

Let us improve this post!

Thanks for your feedback!

## Leave a Reply