Skip to Main Content
Kotlin Cookbook
book

Kotlin Cookbook

by Ken Kousen
November 2019
Intermediate to advanced content levelIntermediate to advanced
254 pages
4h 55m
English
O'Reilly Media, Inc.
Content preview from Kotlin Cookbook

Chapter 7. Scope Functions

The Kotlin standard library contains several functions whose purpose is to execute a block of code in the context of an object. Specifically, this chapter discusses the scope functions let, run, apply, and also.

7.1 Initializing Objects After Construction with apply

Problem

You need to initialize an object before using it, beyond what you can do by supplying constructor arguments.

Solution

Use the apply function.

Discussion

Kotlin has several scoping functions that you can apply to objects. The apply function is an extension function that sends this as an argument and returns it as well. Example 7-1 shows the definition of apply.

Example 7-1. Definition of the apply function
inline fun <T> T.apply(block: T.() -> Unit): T

The apply function is thus an extension function on any generic type T, which calls the specified block with this as its receiver and returns this when it completes.

As a practical example, consider the problem of saving an object to a relational database by using the Spring framework. Spring provides a class called SimpleJdbcInsert, based on JdbcTemplate, which removes the boilerplate from normal JDBC code in Java.

Say we have an entity called Officer that maps to a database table called OFFICERS. Writing the SQL INSERT statement for such a class is straightforward, except for one complication: if the primary key is generated by the database during the save, then the supplied object needs to be updated with the new key. For this ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Functional Kotlin

Functional Kotlin

Mario Arias, Rivu Chakraborty
Kotlin Programming Cookbook

Kotlin Programming Cookbook

Aanand Shekhar Roy, Rashi Karanpuria
Functional Programming in Kotlin

Functional Programming in Kotlin

Runar Bjarnason, Paul Chiusano, Marco Vermeulen
Learning Concurrency in Kotlin

Learning Concurrency in Kotlin

Miguel Angel Castiblanco Torres

Publisher Resources

ISBN: 9781492046660Errata PageSupplemental Content