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:
// Goalval now = Date()val tomorrow = now.plusDays(1) // No such method yet
However, Java’s Date
class has no such plusDays
method. Traditionally, you would create a helper function that allows you to write val tomorrow = plusDays(now, 1)
, but this call syntax has several drawbacks:
- It doesn’t read as naturally
- The function is not scoped to
Date
objects- Thus, autocomplete is a lot less helpful
Fortunately, Kotlin’s extensions can achieve what we want. A plusDays
function that fulfills the requirements above can be written as follows:
fun Date.plusDays(count: Int) = Date(this.time + count * 86400000L)
Note: The function signature contains the
Date
class ...