Working with Anonymous Function in Kotlin
Last Updated :
20 Dec, 2021
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:
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.
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
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 about infix notation used in Kotlin functions. In Kotlin, a function 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 KotlinTable of ContentStandard libr
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
Function Literals with Receiver in Kotlin In Kotlin, functions are first-class citizens. It means that functions can be assigned to the variables, passed as an argument, or returned from another function. While Kotlin is statically typed, to make it possible, functions need to have a type. It exists and it is called function type and these
3 min read