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 ...
Get Kotlin Cookbook 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.