0
0
Kotlinprogramming~5 mins

Local functions (nested functions) in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a local function in Kotlin?
A local function is a function defined inside another function. It helps organize code by grouping related tasks within the outer function.
Click to reveal answer
beginner
How do local functions help in Kotlin programming?
Local functions improve readability and structure by keeping helper code close to where it is used. They also limit the scope, so the local function can't be accessed outside its containing function.
Click to reveal answer
intermediate
Can a local function access variables from its outer function in Kotlin?
Yes, a local function can access and use variables declared in its outer function. This allows sharing data without passing parameters explicitly.
Click to reveal answer
beginner
Write a simple Kotlin function with a local function that prints a greeting.
fun greet() { fun sayHello() { println("Hello!") } sayHello() }
Click to reveal answer
intermediate
Why might you choose a local function over a lambda in Kotlin?
Local functions can have names, making code clearer. They also support recursion and can be easier to debug compared to lambdas.
Click to reveal answer
Where can a local function be declared in Kotlin?
AOnly inside an object
BAt the top level of a file
CInside another function
DInside a class but outside any function
Can a local function access variables from its outer function in Kotlin?
AYes, it can access variables from the outer function
BOnly if variables are declared as global
CNo, it can only access its own variables
DOnly if variables are passed as parameters
What is one advantage of using local functions in Kotlin?
AThey can be called from anywhere in the program
BThey help organize code and limit scope
CThey replace classes
DThey run faster than top-level functions
Which of these is a valid way to define a local function in Kotlin?
Afun outer() { fun inner() { println("Hi") } inner() }
Bfun inner() { fun outer() { println("Hi") } }
Cfun inner() { println("Hi") } fun outer() { inner() }
Dfun outer() { println("Hi") }
Why might you prefer a local function over a lambda expression in Kotlin?
ALocal functions are global
BLocal functions cannot access outer variables
CLambdas are slower to execute
DLocal functions can have names and support recursion
Explain what a local function is in Kotlin and how it can be useful.
Think about functions inside functions.
You got /4 concepts.
    Describe how local functions can access variables from their outer function and why this is helpful.
    Consider variable visibility inside nested functions.
    You got /4 concepts.