Local Functions

We can have functions in classes and similar constructs, such as interfaces.

We can have top-level functions, outside of any class.

And, as it turns out, we can have local functions, where one function resides inside of another function.

I Heard You Like Functions…

A chunk of the Kotlin standard library is written as pure functions: top-level functions that are not part of any class. For these functions, the only input (ideally) comes as parameters.

Even more is written in the form of extension functions on existing classes. Extension functions look like what their name suggests: they extend an existing class. However, from a practical standpoint, extension functions really amount to “syntactic sugar” on top-level functions. An extension function has no ability to do anything that an equivalent top-level function cannot — the extension function simply gets to use this for one of the parameters. So, this:

fun String.withLength() = "$this ${this.length}"

…is equivalent to:

fun stringWithLength(s: String) = "$s ${s.length}"

Pure functions and extension functions have no state. All input is provided via parameters, where the extension function just has convenient syntax for supplying one special parameter (this).

However, since these sorts of functions have no state, sub-dividing them into smaller functions can be a problem sometimes. You might have a really complex function where a piece of logic ought to be pulled out into a separate function, but both the original and the separate function share too many values.

You may also have cases where you want to pull logic out into a separate function, but that separate function has no purpose except when called in the context of its original function.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.