Updated March 30, 2023
Introduction to Kotlin Higher Order Functions
The kotlin higher order function is one of the functions that can be accepted, or it may be returned with another type of function. The main method is invoked by passing the string type of arguments and function as the arguments that well known as higher function and also it calls the regular function by passing the parameter arguments so that it returns the output results of operation invocation with the supplied arguments to declare the function that can be matched only the operation signature like arguments it also passes anonymous function or lambdas.
Syntax of Kotlin Higher Order Functions
In kotlin language, we already know about the default classes, methods, variables and other pre-defined keywords. Like that, higher order is one of the functions it may cover using the anonymous and lambda type of functions. Most frequently, lambdas are passed as parameters in kotlin functions.
var vars1={some statements}
fun methods1(vars2: () -> Unit)
{
vars2()
}
fun main(args:Array<String>)
{
methods1(vars1)
}
The above codes are the basic syntax for to utilising the higher order functions on the kotlin language. In addition, it accepts and passes some anonymous and lambda expressions. Finally, it will return the results based on the specific datatype which is used on the methods.
How do Higher Order Functions work in Kotlin?
The higher order function is the type of function that can be covered using the anonymous and lambda type of expressions. It also stores functions in variables, we can also pass them as the arguments to the other type of functions that may be both built-in and other customized functions, and even it can be returned the function from a function. So when we want to define the function that accepts the function as an argument or returns the function from it, we can call it to the higher order function than the default and customised functions.
Whenever we declare the higher-order function, it will take upto two types of arguments; additionally, we take another function parameter if needed on the logic. The other function parameter and its return type are also the same and defined in the declaration type. So that higher order function returns the result of operation invocation with the other supplied parameters and its return type. So we can declare the function that can be matched using the specified signature, and it may be the same with both the function parameters. The two function parameters::sum . :: these are the default notation and are used as the reference for the kotlin function name. Lambda and anonymous functions are used to operate these higher order functions.
Examples of Kotlin Higher Order Functions
Different examples are mentioned below:
Example #1
Code:
import java.util.Scanner
fun examp1(st1: String,st2: String, exmp: (String,String) -> String): Unit {
val out = exmp(st1,st2)
println(out)
}
fun <T> ArrayList<T>.filterOnCondition(condition: (T) -> Boolean): ArrayList<T>{
val rst = arrayListOf<T>()
for (itm in this){
if (condition(itm)){
rst.add(itm)
}
}
return rst
}
fun main(args: Array<String>) {
try {
val inp = Scanner(System.`in`)
println("Welcome To My Domain its the first example that related to the kotlin higher oder function")
println("Please enter your inputs")
var id = inp.nextInt()
println("Your input id is "+id)
val lamb: (Int) -> Unit= {st: Int -> println(st) }
demo(74,12,lamb)
val inpdata = 16 / 4
println(inpdata)
}
catch (e: NullPointerException) {
println(e)
} finally {
println("finally block always executed whenever try is executing")
}
println("Have in Nice Day users please try again")
val exmp:(String,String)->String={st1,st2->"$st1 assigned and it will be automatically goes to $st2"}
examp1("Welcome To My Domain","Have a Nice day users",exmp)
var lst = arrayListOf<String>()
lst.add("January is the first month")
lst.add("February is the second month`")
lst.add("March is the third month")
lst.add("April is the fourth month")
lst.add("May is the fifth month")
lst.add("June is the sixth month")
lst.add("July is the seventh month")
lst.add("August is the eigth month")
lst.add("September is the ninth month")
lst.add("October is the tenth month")
lst.add("November is the eleventh month")
lst.add("December is the twelth month")
var modifiedList = lst.filterOnCondition { it.contains("six") }
val fp = { print("Have a Nice day users please continue to spenting your time with us") }
sec(fp)
}
fun sec(fp: () -> Unit) {
fp.invoke()
}
fun demo(in1: Int, in2: Int,lamb: (Int) -> Unit){
val result = in1 + in2
println(result)
}
Output:
In the above example, we used lambda expressions and collection concepts with higher order functions.
Example #2
Code:
fun main(args: Array<String>) {
var lmbfun :(String)->Unit = {s:String -> println(s)}
lmbfun("Welcome To My Domain its the first example related to the kotlin higher order function")
lmbfun = {println(it)}
lmbfun("Have a Nice day users please try again")
val anony : () -> Unit ={ println("The kotlin higher order function operated and executed")}
anony()
var demo: (String) -> Unit = { println(it) }
examp("June is the current month", ::demo)
var lst = listOf<Int>(3,6,9,12,15,18,21,24,27,30)
lst = lst.filter(fun(itm) = (itm%2 ==0) )
println(lst)
var out = 0
lst = listOf(3,6,9,12,15,18,21,24,27,30)
lst.forEach { out+=it }
println(out)
}
fun examp(st: String, st1: (String) -> Unit) {
print("The kotlin higher order function is performed using some collection list")
st1(st)
}
fun demo(str: String) {
println(str)
}
Output:
In the second example, we used the collection concept with a higher order function.
Example #3
Code:
fun main(args: Array<String>) {
val inp = calsquares()
println("Welcome To My Domain its the third example related to the kotlin higher order function")
println(inp(9))
println(inp(11))
val inp1 = exam1()
inp1("Your input values are squared using the calsquares function")
}
fun calsquares() : (Int) -> Int {
return {x -> x * x}
}
fun exam2(st1: String){
println("This is another method using the concept as higher order function")
println("Your input string values are $st1")
}
fun exam1(): (st1:String) -> Unit{
println("This is the final method using the higher order function concept")
return ::exam2
}
Output:
In the final example, we performed the operations like a square of the numbers with higher order functions.
Conclusion
In kotlin, a higher order function is the type of function similar to the other kotlin built-in functions. This can be achieved and applied to the kotlin language with the help of lambda and anonymous order functions. An operator like:: performs the higher order function and returns the same function as the return type.
Recommended Articles
This is a guide to Kotlin Higher Order Functions. Here we discuss the introduction, syntax, and working of higher-order functions in Kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –