Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data Types
  • Array
  • String
  • Functions
  • Collections
  • Oops
  • Android
  • Android Studio
  • Kotlin Android
  • Android Projects
  • Android Interview Questions
Open In App
Next Article:
How to Use try - catch as an Expression in Kotlin?
Next article icon

How to Pass a Function as a Parameter to Another in Kotlin?

Last Updated : 11 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Kotlin gives us the power to declare high-order functions. In a high-order function, we can pass and return functions as parameters. This is an extremely useful feature and makes our code much easier to work with. In fact, many of the Kotlin library's functions are high order, such as NBQ. In Kotlin, we can declare functions and function references as values that are then passed into the function. We will first understand how to declare lambdas and then how to pass them into a function.

Example

Let's start by understanding how we declare functions as lambdas:

Kotlin
fun main (args: Array<String>) {   val funcMultiply - {a: Int, b: Int -> a*b}   println (funcMultiply (4, 3))   val funcSayHi - {name: String -> println ("Hi $name") }   funcSayHi("John") } 

In the preceding code block, we declared two lambdas: one (funcMultiply) that takes two integers and returns an integer, and another (funcSayHi) lambda that takes a string and returns a unit-that is, it returns nothing. Although we did not need to declare the type of arguments and the return type in the preceding example, in some cases we need to explicitly declare the argument types and return types. We do this in the following way:

Kotlin
fun main (args: Array<String>) {   val funcMultiply : (Int, Int)->Int = {a: Int, b:Int -> a*b}   println (funcMultiply (4, 3))   val funcSayHi : (String) ->Unit = {name: String -> println("Hi $name")}   funcSayHi ("John") } 

So now that we have a general idea of how lambdas work, let's try and pass one in another function-that is, we will try a high-order function. Check out this code snippet:

Kotlin
fun main (args: Array<String>) {    val funcMultiply : (Int, Int) ->Int = {a: Int, b:Int -> a*b}   val funcSum : (Int, Int) ->Int = {a: Int, b: Int -> a+b}   performMath (3, 4, funcMultiply)   performMath (3, 4, funcSum) }  fun performMath (a: Int, b:Int, mathFunc : (Int, Int) -> Int) : Unit {   println ("Value of calculation: ${mathFunc (a, b) }") } 

It is as simple as that-create a function lambda and pass it into the function. So this is just one aspect of a high-order function-that is, we can pass a function as an argument to the function. Another use of high-order functions is to return a function. Consider the following example where we need a function that transforms the total price of an order according to certain conditions. Kind of like an e-commerce site, but way simpler

Kotlin
fun main(args: Array<String>) {   // free delivery of order above 499   val productPricel = 600;    // not eligible for free delivery   val productPrice2 = 300;    val totalCost1 = totalCost (productPrice1)   val totalCost2 = totalCost (productPrice2)      println("Total cost for item 1 is ${totalCost1 (productPrice1) }")   println ("Total cost for item 2 is ${totalCost2 (productPrice2) }") }  fun totalCost (productCost : Int) : (Int) -> Int(   if (productCost > 499) {     return { x -> x }   }   else {     return { x -> x + 50 }   } } 

Note how we need to change functions that we apply based on certain conditions so that we return a function that suits the conditions. We assign the returned function to a variable and then we can just put append () in front of the variable to use it as a function, just like we did with the lambdas. This works because the high-order function is essentially returning a lambda.

In Kotlin, we can assign a function to a variable, and then we can pass it into a function or return it from a function. This is because it's essentially declared like a variable. This is done using a lambda declaration of functions.


Next Article
How to Use try - catch as an Expression in Kotlin?

E

eralokyadav2019
Improve
Article Tags :
  • Kotlin
  • Kotlin Functions

Similar Reads

  • Passing Variable Arguments to a Function in Kotlin
    There are a lot of scenarios in which we need to pass variable arguments to a function. In Kotlin, You can pass a variable number of arguments to a function by declaring the function with a vararg parameter. a vararg parameter of type T is internally represented as an array of type T ( Array<T
    4 min read
  • How to Write swap Function in Kotlin using the also Function?
    also is an extension function to Template class which takes a lambda as a parameter, applies contract on it, executes the lambda function within the scope of calling object, and ultimately returns the same calling object of Template class itself. Swapping two numbers is one of the most common things
    3 min read
  • How to Use try - catch as an Expression in Kotlin?
    The try statement consists of a try-block, which contains one or more statements. { } must always be used, even for single statements. A catch-block, a finally-block, or both must be present. This gives us three forms for the try statement: try...catchtry...finallytry...catch...finally A catch-block
    4 min read
  • How to Throw a Custom Exception in Kotlin?
    In addition to the built-in Exception Classes, you can create your own type of Exception that reflects your own cause of the exception. And you will appreciate the use of Custom Exception when you have multiple catch blocks for your try expression and can differentiate the custom exception from regu
    2 min read
  • How to Specify Default Values in Kotlin Functions?
    In Kotlin, you can provide default values to parameters in a function definition. If the function is called with arguments passed, those arguments are used as parameters. However, if the function is called without passing argument(s), default arguments are used. But If you come from the Java world,
    4 min read
  • How to Convert a Kotlin Source File to a Java Source File in Android?
    We use Android Studio to translate our Java code into Kotlin while transitioning from Java to Kotlin. But what if we need to convert a Kotlin file to its Java equivalent? We'll examine how to convert a Kotlin source file to a Java source file in this blog. Let's get this party started. Because of it
    2 min read
  • How to add a custom styled Toast in Android using Kotlin
    A Toast is a short alert message shown on the Android screen for a short interval of time. Android Toast is a short popup notification that is used to display information when we perform any operation in the app. In this article, let's learn how to create a custom toast in Android using Kotlin. To c
    4 min read
  • Function Return and Type Hierarchy in Kotlin
    Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, App code, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a “better
    4 min read
  • How to Build a Simple Torch App in Android using Kotlin?
    Torch Application is a very basic application that every beginner level android developer should definitely try to build while learning Android. In this article, we will be creating an application in which we will simply display a toggle button to switch on and switch off the torch. Note: If you are
    4 min read
  • How to Convert Text to Speech in Android using Kotlin?
    Text to Speech App converts the text written on the screen to speech like you have written “Hello World” on the screen and when you press the button it will speak “Hello World”. Text-to-speech is commonly used as an accessibility feature to help people who have trouble reading on-screen text, but it
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences