0% found this document useful (0 votes)
2 views3 pages

Higher-Order Function in Kotlin

Uploaded by

manojkdh30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Higher-Order Function in Kotlin

Uploaded by

manojkdh30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Alright 👍 let’s go step by step.

✅ What is a Higher-Order Function in Kotlin?


A higher-order function is a function that either:

1.​ Takes another function as a parameter, OR​

2.​ Returns a function as a result.​

This makes Kotlin very powerful for functional programming.

📌 Example 1: Function as a Parameter


fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {

return operation(x, y)

fun main() {

val sum = calculate(5, 3) { a, b -> a + b }

val product = calculate(5, 3) { a, b -> a * b }

println("Sum: $sum")

println("Product: $product")

👉 Output:
Sum: 8
Product: 15

Here, operation is a function passed as a parameter.

📌 Example 2: Function Returning Another Function


fun multiplyBy(factor: Int): (Int) -> Int {

return { number -> number * factor }

fun main() {

val times2 = multiplyBy(2)

val times3 = multiplyBy(3)

println(times2(5)) // 10

println(times3(5)) // 15

Here, multiplyBy returns a function that multiplies a number by the given factor.

🎯 Uses of Higher-Order Functions


1.​ Code Reusability – Instead of repeating logic, pass behavior as a function.​

2.​ Functional Programming Style – Makes code concise and expressive.​


3.​ Callback Functions – Useful in Android development (e.g., button clicks, API
responses).​

4.​ Collections Operations – Functions like map, filter, forEach, and reduce are
higher-order functions.​

5.​ Cleaner Asynchronous Programming – Used in coroutines, lambdas, and event


handling.​

👉 Example in Real Life (Android):


[Link] {

println("Button Clicked!")

Here, setOnClickListener is a higher-order function because it takes a function (lambda) as


a parameter.

Do you want me to also make a PDF note (like I did for Enum Class) for this so you can keep
it for UPSC + Android prep?

You might also like