
Member-only story
Kotlin’s way to make DSLs and many standard library functions work
Kotlin Function Literals with Receiver — The basis for DSLs and many Library Functions
As we know, Kotlin makes heavy use of functions that take other functions as their argument. This is one of two types of functions we call higher-order function. Related to this, Kotlin also comes with first-class support for passing functions around using function literals. There are two types of function literals: lambdas and anonymous functions. The entire standard library wouldn’t be half as powerful if it wasn’t using any higher-order functions.
Typical examples of higher-order functions in Kotlin are candidates such as map
, filer
or fold
as can be used for collections.
On top of that, there’s a special type of higher-order function that adds a very important tool to the language: Function literals passed to other functions can work with a so called receiver to improve both the call and the definition side. In this article, I will be explaining how to identify, write and use those function literals in your code. A popular example of this kind of function is used with the apply
scope function that is shown in the following example:
Isn’t it interesting that age
can be accessed without naming the object as in person.age
? How is this structure made possible?
The entire concept of function literals with receiver is what makes Kotlin a great choice for designing Domain Specific Languages.
Same basics
Kotlin, other than Java, has proper function types, which means that variables can represent a type such as a function accepting an integer and returning a string:
(Int) -> String // a function type
We can use those function types as parameters for other functions. We call those functions "higher-order functions".