Jagdeep SinghJagdeep Singh
Navigate back to the homepage

The fun of Kotlin - Local Functions

Jagdeep Singh
April 4th, 2021 · 1 min read

The fun of Kotlin — Local Functions

In Kotlin, functions are the first class citizens. In this series I’ll be talking about some super cool features of Kotlin functions.

Pit stops

  1. Local functions. (you’re here)
  2. Infix functions.
  3. Anonymous functions.
  4. Inline functions.
  5. Returns and local returns.

Who should read?

This post is for all the Kotlin lovers and those people who are learning or want to learn Kotlin.


I’d recommend that, before moving forward, you have basic knowledge of Kotlin language syntax such as how to define variables, classes and functions. Official website of Kotlin is the best place to learn the basic syntax of the language.

Local functions

A local function is a function inside another function. Yes, you can do that in Kotlin. Here is an example.

1fun outerFunction(nice: String) {
2 val hello = "Hello, world"
4 fun innerFunction(awesome: String) {
5 println(awesome)
7 // we can access arguments of outer function
8 println(nice)
10 // and we can also access variables declared in outer functions
11 println(hello)
12 }
14 // invoking inner function
15 innerFunction("This is awesome")
18fun main(args: Array<String>) {
20 // we can access outerFunction but not innerFunction outside of the
21 // outerFunction's scope
22 outerFunction("This is nice")

But, what’s the use of Local functions? We can just create member functions in classes to achieve our goal.

Local functions are useful when we want to reuse some code but do not want to create a member function because it will be invoked from just one function. Local functions can help us reduce the number of member functions in classes and still be able to reuse the code.

Also, Local functions are only accessible inside the function in which they are defined.

Access modifiers like public, private are not allowed on Local functions.

Official documentation about Local functions

Thank you for taking your time to read this article. If you have any questions, suggestions on how to improve this articles, please feel free to contact me on twitter :)

Jagdeep Singh (@jsmundi)

More articles from Jagdeep Singh

The fun of Kotlin — Infix Functions

In the previous part of this series, we learned about Local functions in Kotlin. I this part, I’d like to talk about Infix functions. Infix notation makes function calls look super awesome.

April 4th, 2021 · 1 min read

Realtime access to production logs — Android

Papertrail-timber gives you an already configured Timber Tree that you can just plant in Timber and ready to go.

March 7th, 2018 · 2 min read
© 2018–2021 Jagdeep Singh
Link to $https://twitter.com/jsmundi/Link to $https://github.com/jdsingh/Link to $https://www.linkedin.com/in/jagdeepsinghmundi/