Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

Function literals


Just like we define string literals, hello, or double literals (12.34), we can also define function literals. To do so, we simply enclose the code in braces:

    { println("I am a function literal") } 

Function literals can be assigned to a variable just like other literals:

    val printHello = { println("hello") } 
    printHello() 

Notice in this example that once a function literal is defined, we can invoke it later using parentheses, like we do for a regular function. Of course, once defined, we can invoke the function multiple times.

Function literals can also accept parameters. For this, we write the parameters, along with types, before a thin arrow; this denotes the function body:

    val printMessage = { message: String -> println(message) } 
    printMessage("hello") 
    printMessage("world") 

As you can see, we pass in the parameter when invoking like a regular function. When a function literal is used in a place where the compiler...