Jagdeep Singh
Jagdeep's blog

Jagdeep's blog

The fun of Kotlin - Local Functions

The fun of Kotlin - Local Functions

Jagdeep Singh's photo
Jagdeep Singh
·Apr 4, 2021·

2 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.

Prerequisite

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.

fun outerFunction(nice: String) {
    val hello = "Hello, world"

    fun innerFunction(awesome: String) {
        println(awesome)

        // we can access arguments of outer function
        println(nice)

        // and we can also access variables declared in outer functions
        println(hello)
    }

    // invoking inner function
    innerFunction("This is awesome")
}

fun main(args: Array<String>) {

    // we can access outerFunction but not innerFunction outside of the 
    // outerFunction's scope
    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

 
Share this