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 Write swap Function in Kotlin using the also Function?
Next article icon

Working with Anonymous Function in Kotlin

Last Updated : 20 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In Kotlin, we can have functions as expressions by creating lambdas. Lambdas are function literals that is, they are not declared as they are expressions and can be passed as parameters. However, we cannot declare return types in lambdas. Although the return type is inferred automatically by the Kotlin compiler in most cases, for cases where it cannot be inferred on its own or it needs to be declared explicitly, we use the anonymous functions. In this article, we will see how to use anonymous functions. Before that we have some:

Prerequisites for this Article:

  • Functions in Kotlin

Basic Idea of these:

  • Lambda Expression (it is a short way to define a function.)
  • Anonymous Function (it is an alternative way to define a function.)

Refer to this article: Lambdas Expressions and Anonymous Functions

Example

We will learn about anonymous functions Step-by-Step with the help of some examples:

Let's start by declaring a function as a lambda:

Kotlin
fun main(args: Array<String>){     val funMultiply = {a : Int, b : Int-> a * b}      printIn(funMultiply(6,4))     val funSayHi = {name : String->println("Hi $name")}     funSayHi("geek") } 

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

Kotlin
fun main (args: Array<String>){   var funMultiply = fun (a: Int, b: Int) : Int {return a*b}   printin (funMultiply (6,4))   fun (name : String) : Unit = println ("Hi $name") } 

So now we have a general idea of how anonymous functions work. Now, 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>){     var funMultiply = fun(a: Int, b: Int) : Int { return a*b }     var funSum = fun(a: Int, b: Int) : Int { return a+b }     performMath (6, 4, funMultiply)     performMath (6, 4, funSum) } fun performMath (a : Int, b: Int, mathFun : (Int, Int) -> Int) : Unit {     printIn ( "Value of calculation: ${mathFun(a, b)}") } 

So basically, an anonymous function is declared just like a regular function, but without a name. The body can be an expression, as in the following example, or a block, as in the preceding example. One thing to note is that parameters are always passed inside the parentheses in the case of anonymous functions, unlike in lambda expressions:

Kotlin
fun main (args: Array<String>) {     performMath (6,4, fun (a: Int, b: Int) : Int = a*b )     performMath (6,4, fun (a: Int, b: Int) : Int = a+b ) } fun performMath (a : Int, b: Int, mathFun : (Int, Int) -> Int) : Unit {     println ("final value: ${mathFun(a,b)}") } 
  • Another interesting difference between a lambda and an anonymous function is that in a lambda, the return statement returns from the enclosing function, whereas in an anonymous function, it simply returns from the function itself.
  • One can omit the parameter type and return type from an anonymous function as well if it can be inferred on its own.
  • Anonymous functions can access and modify variables inside their closures.

So basically, one can declare an anonymous function just like a regular function without a name (hence, the name anonymous ). It can be an expression or a code block.


Next Article
How to Write swap Function in Kotlin using the also Function?

E

eralokyadav2019
Improve
Article Tags :
  • Kotlin
  • Kotlin Functions

Similar Reads

  • Transform a List Using Map Function in Kotlin
    Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, 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
    3 min read
  • Suspend Function In Kotlin Coroutines
    Prerequisite: Kotlin Coroutines on Android The Kotlin team defines coroutines as “lightweight threads”. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin coroutines introduce a
    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
  • withContext in Kotlin Coroutines
    Prerequisite: Kotlin Coroutines on AndroidLaunch vs Async in Kotlin Coroutines It is known that async and launch are the two ways to start the coroutine. Since It is known that async is used to get the result back, & should be used only when we need the parallel execution, whereas the launch is
    3 min read
  • Kotlin Function Variations With Examples
    While defining a function in Kotlin we have many optional annotations. We will learn each of them one by one. Defining a function in Kotlin: Visibility modifier fun functionName (argument name: type name, ...): return type{ ..... // function body ..... return value } Normally, It is the proper way f
    3 min read
  • 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
  • Kotlin infix function notation
    In this article, we will learn infix notation used in Kotlin functions. In Kotlin, a functions marked with infix keyword can also be called using infix notation means calling without using parenthesis and dot. There are two types of infix function notation in Kotlin-   Standard library infix functio
    5 min read
  • Local Functions in Kotlin
    The idea behind functions is very simple: split up a large program into smaller chunks that can be reasoned more easily and allow the reuse of the code to avoid repetition. This second point is known as the DRY principle: Don't Repeat Yourself. The more the number of times you write the same code, t
    5 min read
  • Jobs, Waiting, Cancellation in Kotlin Coroutines
    Prerequisite: Kotlin Coroutines On AndroidDispatchers in Kotlin CoroutinesSuspend Function In Kotlin Coroutines In this article, the following topics will be discussed like what are the jobs in a coroutine, how to wait for the coroutine, and how to cancel the coroutine. Whenever a new coroutine is l
    7 min read
  • How to Work With Nested Class in Kotlin?
    A class is declared within another class then it is called a nested class. By default nested class is static so we can access the nested class property or variables using dot(.) notation without creating an object of the class. Syntax of declaration:  class outerClass { ............ // outer class p
    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