Anonymous Functions

Anonymous functions are an essential part of Kotlin. One way they are used is to allow you to easily customize how built-in functions from the Kotlin standard library work to meet your particular needs. An anonymous function lets you describe additional rules for a standard library function so that you can customize its behavior. Let’s look at an example.

One of the many functions in the standard library is count. When called on a string, count returns the total number of letters in the string. The following code counts the letters in the string "Mississippi":

    val numLetters = "Mississippi".count()
    print(numLetters)
    // Prints 11

(Here you have used dot syntax to invoke the count function. This syntax ...

Get Kotlin Programming: The Big Nerd Ranch Guide, First Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.