Left Index

Kotlin Lamdas

In this article, we are going to learn lambdas expression and anonymous function in Kotlin. While syntactically similar, Kotlin and Java lambdas have very different features.

Lambdas expression and Anonymous function both are function literals means these functions are not declared but passed immediately as an expression.


Lambda Expression: Syntax of Kotlin Lamdas

Syntax:
val name: Return Type = { arguments -> codeBody }

A lambda expression is always surrounded by curly braces, argument declarations go inside curly braces and have optional type annotations, the code_body goes after an arrow -> sign. If the inferred return type of the lambda is not Unit, then the last expression inside the lambda body is treated as return value.


Note: Apart from codeBody in syntax all are optional, let's create an example:

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) { 
	val company = { println("The It Bulls")}
	// invoking function method1 
	company() 

	// invoking function method2 
	company.invoke() 
} 
Output:
The It Bulls
The It Bulls

Now let's create an Kotlin Lamdas with two parameter for addition:

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) { 
	val sum = {a: Int, b: Int -> a + b}
	println("Sum: " + sum(3, 5))
	
	
	// Type Declaration
	val sum1:(Int, Int) -> Int = {a, b -> a + b}
	println("Sum1: " + sum1(3, 5))

	// Unit is like java void
	val sum2:(Int, Int) -> Unit = {a, b ->
		var s = a + b
		println("Sum3 of: ${s}")
	}
	
	sum2(10, 20)
} 
Output:
Sum: 8
Sum1: 8
Sum3 of: 30