Lesson 37: – Higher Order Functions in kotlin

Lesson 37: – Higher Order Functions in kotlin

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

Kotlin is an object-oriented language but introduces features in functional languages that allow us to create a clearer and more expressive code.

One of the characteristics of the functional programming paradigm is the higher order functions.

The higher order functions are functions that can receive as parameters other functions and/or return them as results.

We will see a series of very simple examples to see how Kotlin implements the concept of functions of higher order and as we advance in the course we will be able to see the advantages of this paradigm.

Problem 1

Define a higher order function called operate. They arrive as a parameter two integers and a function. In the function block call the function that arrives as a parameter and send the first two parameters.
The function returns an integer.

Project147 – Principal.kt

fun operate (v1: Int, v2: Int, fn: (Int, Int) -> Int): Int {
    return fn (v1, v2)
}

fun sum (x1: Int, x2: Int) = x1 + x2

fun sub (x1: Int, x2: Int) = x1 - x2

fun multiply (x1: Int, x2: Int) = x1 * x2

fun divide (x1: Int, x2: Int) = x1 / x2

fun main (parameter: Array <String>) {
    val resu1t1 = operate (10, 5, :: sum)
    println ("The sum of 10 and 5 is $resu1t1")
    
    val result2 = operate (5, 2, :: sum)
    println ("The sum of 5 and 2 is $result2")
    
    println ("Subtraction of 100 and 40 is ${operate (100, 40, :: sub)}")
    println ("The product between 5 and 20 is ${operate (5, 20, :: multiply)}")
    println ("The division between 10 and 5 is ${operate (10, 5, :: divide)}")
}

We have defined 6 functions in this problem. The only higher order function is called “operate”:

Fun operate(v1: Int, v2: Int, fn: (Int, Int) -> Int): Int {
    Return fn (v1, v2)
}

The third parameter of this function is called “fn” and is of type function. When a parameter is of type function we must indicate the parameters that have this function (in this case has two integer parameters) and then the -> operator of the data type that returns this function:

Fn: (Int, Int) -> Int

When we have a function as a parameter that does not return data the unit type is indicated, for example:

Fn: (Int, Int) -> Unit

The algorithm of the operate function consists of calling the function fn and passing the two integers that the function expects:

    Return fn (v1, v2)

As the function operate returns an integer we must indicate with the return keyword that it returns the data that returns the function “fn”.

The four functions that calculate addition, subtraction, multiplication, and division have nothing new as seen in previous concepts:

Fun sum (x1: Int, x2: Int) = x1 + x2

Function sub (x1: Int, x2: Int) = x1 - x2

Fun multiply (x1: Int, x2: Int) = x1 * x2

Fun divide (x1: Int, x2: Int) = x1 / x2

In the function main we call the function operate and we pass three data, two integers and one with the reference of a function:

    Val result1 = operate (10, 5, :: sum)

As we see to pass the reference of a function we precede the operator ::

The operate function returns an integer and stores it in the variable resu1 which we then display:

    Println ("The sum of 10 and 5 is $result1")

It is important to imagine the operation of the operate function that receives three data and uses one of them to call another function that returns a value and then returns this value to operate and finally reaches the variable “result1“.

We call to operate and we pass again the reference to the add function:

    Val result2 = operate (5, 2, :: sum)
    Println ("The sum of 5 and 2 is $result2")

In a similar way we called to operate and passed the references to the other functions:

    Println ("Subtraction of 100 and 40 is ${operate (100, 40, :: sub)}")
    Println ("The product between 5 and 20 is ${operate (5, 20, :: multiply)}")
    Println ("The division between 10 and 5 is ${operate (10, 5, :: divide)}")

Note that to add two integers it is better to directly call the add function and to pass the two integers, but the objective of this problem is to know the syntax of the higher order functions presenting the simplest problem.

The higher order functions can be used perfectly in the methods of a class.

Problem 2

Declare a class that stores the name and age of a person. Define a method that returns true or false depending on whether the person is of legal age or not. This function should receive as a parameter a function that when called after the age of the person will return if it is older or not old.
Keep in mind that a person is of legal age in the United States if he is 21 or older and in Argentina, if he is 18 or older.

Project148 – Principal.kt

class Person (val name: String, val age: Int) {
    fun isMajor (fn: (Int) -> Boolean): Boolean {
        return fn (age)
    }
}

fun majorUnitedStates (age: Int): Boolean {
    if (age >= 21)
    return true
    else
    return false
}

fun majorArgentina (age: Int): Boolean {
    if (age >= 18)
    return true
    else
    return false
}

fun main (parameter: Array <String>) {
    val person1 = Person ("juan", 18)
    if (person1.isMajor (:: majorArgentina))
        println ("${person1.name} is greater if you live in Argentina")
    else
        println ("${person1.name} is not greater if you live in Argentina")
    if (person1.isMajor (:: majorUnitedStates))
        println ("${person1.name} is greater if you live in the United States")
    else
        println ("${person1.name} is not greater if you live in the United States")
}

We declare the class Person with two properties called name and age:

Class Person (val name: String, val age: Int) {

The class person by itself does not keep the nationality of the person, instead of when asked if it is of age is passed as a reference a function that when passing the age returns us true or false:

    Fun isMajor (fn: (Int) -> Boolean): Boolean {
        Return fn (age)
    }

We have two functions that when passing an age we return if it is of age or not:

Fun majorUnitedStates(age: Int): Boolean {
    If (age>= 21)
        Return true
    Else
        Return false
}

Fun majorArgentina (age: Int): Boolean {
    If (age> = 18)
        Return true
    Else
        Return false
}

In the main function we create an object of the class person:

    Val person1 = Person ("juan", 18)

We call the isMajor method of the person1 object and pass it the reference of the function “majorArgentina”:

    If (person1.isMayor (:: majorArgentina))
        Println ("${person1.name} is greater if you live in Argentina")
    Else
        Println ("${person1.name} is not greater if you live in Argentina")

Now we call the isMajor method but passing the reference of the function “majorUnitedStates”:

    If (person1.isMayor (:: majorUnitedStates))
        Println ("${person1.name} is greater if you live in the United States")
    Else
        Println ("${person1.name} is not greater if you live in the United States")

As we can verify the concept of higher order functions is applicable to the methods of a class.

We did not make a more concise code with the object that clarifies the syntax of higher order functions, but the same problem can be:

Class Person (val name: String, val age: Int) {
    Fun isMajor (fn: (Int) -> Boolean) = fn (age)
}

Fun majorUnitedStates (age: Int) = if (age>= 21) true else false

Fun majorArgentina (age: Int) = if (age>= 18) true else false

Fun main (parameter: Array <String>) {
    Val person1 = Person ("juan", 18)
    If (person1.isMayor (:: majorArgentina))
        Println ("${person1.name} is greater if you live in Argentina")
    Else
        Println ("${person1.name} is not greater if you live in Argentina")
    If (person1.isMayor (:: majorUnitedStates))
        Println ("${person1.name} is greater if you live in the United States")
    Else
        Println ("${person1.name} is not greater if you live in the United States")
}

 

About The Author

Related posts

Leave a Reply