Member-only story

Understand Kotlin Function Literal with Receiver by Example

This article provides some simple code examples of using function literal with receiver (also known as lambda/anonymous function with receiver).

Vincent Tsen
3 min readFeb 11, 2022

I came across this lambda syntax — NavGraphBuilder.() -> Unit and it turns out it is called Function Literal with Receiver, which is also known as Lambda/Anonymous Function with Receiver.

The syntax looks like this:

Receiver.(Parameters) → ReturnType

The following shows some examples of building a custom string using function literal with receiver.

Example 1: Function Literal With Receiver

fun buildCustomStringExample1(
action: StringBuilder.(String) -> Unit): String {

val stringBuilder = StringBuilder()
stringBuilder.action("Example1")
return stringBuilder.toString()
}

action is the function literal / lambda function with receiver. StringBuilder is the receiver. It acts like an extension function of StringBuilder which takes in the string as input parameter.

To call action, StringBuilder is instantiated, call it like an extension function …

--

--

No responses yet