Higher Order Functions and Function Types in Kotlin With Examples

package com.example.my_kotlin_practice

fun main(args: Array<String>) {

// A higher-order function is a function that takes another function as parameter and/or returns a function.

println(square(2))
var sq:(Int)->Int = ::square
println("Square of 8 is : ${sq(8)}")

var result = calculate4(4,5,::sum1)
println("Result is : $result")

var a = 10
var b = 20
arithmeticOperation(a,b,::add)
arithmeticOperation(a,b,::sub)
arithmeticOperation(a,b,::mul)
arithmeticOperation(a,b,::div)
}
fun square(num: Int): Int {
return num*num
}

fun sum1(a:Int,b: Int) = a + b

fun calculate4(a:Int,b:Int, operation:(Int,Int) -> Int):Int {
return operation(a,b)
}
fun add(x:Int,y: Int): Int {
return x + y
}
fun sub(x:Int,y: Int): Int {
return x - y
}
fun mul(x:Int,y: Int): Int {
return x * y
}
fun div(x:Int,y: Int): Int {
return x/y
}

fun arithmeticOperation(a:Int,b:Int,fn:(Int,Int) -> Int) {
var result = fn(a,b)
println("Arithmetic Result is : $result")
}

OUTPUT :

4 Square of 8 is : 64 Result is : 9 Arithmetic Result is : 30 Arithmetic Result is : -10 Arithmetic Result is : 200 Arithmetic Result is : 0 Process finished with exit code 0

Comments

Popular posts from this blog

Maps (Collections) in kotlin

Functions in Kotlin

Arrays in Kotlin