Extension Functions

Understand Kotlin's extension functions, how to define them, and why they are a fundamental feature of Kotlin.

Extension functions allow you to attach new functions to existing types. This includes ones that you don’t own, such as Int, String, any predefined Java class such as Date, Instant, and any type imported from a library.

Typically, this is done using utility classes that encapsulate a series of utility functions. You may be familiar with class names such as StringUtils or DateUtils. In Kotlin, missing capabilities of a class you want to use can be patched using extension functions instead.

Defining an Extension Function #

Let’s say you want to use Java’s old Date class (instead of the java.time package). In your application, you want to add a number of days to a given Date. Ideally, you’d want to write the following:

Get hands-on with 1400+ tech skills courses.