0
0
Kotlinprogramming~10 mins

Local functions (nested functions) in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a local function inside main.

Kotlin
fun main() {
    fun [1]() {
        println("Hello from local function")
    }
    greet()
}
Drag options to blanks, or click blank then click option'
Agreet
Bhello
CsayHello
DlocalFunc
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different function name than the one called.
Defining the function outside main.
2fill in blank
medium

Complete the code to call the local function inside main.

Kotlin
fun main() {
    fun greet() {
        println("Hi there!")
    }
    [1]()
}
Drag options to blanks, or click blank then click option'
Agreet
Bhello
CsayHello
DlocalFunc
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a function name that is not defined.
Forgetting the parentheses to call the function.
3fill in blank
hard

Fix the error by completing the code to return the sum using a local function.

Kotlin
fun sumNumbers(a: Int, b: Int): Int {
    fun add() = a [1] b
    return add()
}
Drag options to blanks, or click blank then click option'
A/
B-
C*
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Forgetting to return the result of the local function.
4fill in blank
hard

Fill both blanks to create a local function that checks if a number is even.

Kotlin
fun main() {
    fun [1](num: Int): Boolean {
        return num [2] 2 == 0
    }
    println(isEven(4))
}
Drag options to blanks, or click blank then click option'
AisEven
B%
C/
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using division / instead of modulus %.
Naming the function something unrelated.
5fill in blank
hard

Fill all three blanks to create a local function that filters and returns words longer than 3 letters.

Kotlin
fun main() {
    val words = listOf("cat", "house", "dog", "elephant")
    fun filterLongWords(list: List<String>): List<String> {
        return list.filter { word -> word.[1] > [2] }
    }
    val result = filterLongWords(words)
    println(result) // Should print words longer than [3] letters
}
Drag options to blanks, or click blank then click option'
Alength
B3
Dsize
Attempts:
3 left
💡 Hint
Common Mistakes
Using word.size which is not valid for strings.
Using the wrong number for comparison.
Confusing length with size.