Menu
Coddy logo textTech

Passing Functions

Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 28 of 63.

A higher-order function accepts a function value or returns one. Declare a function parameter with a function type, then call it inside the helper. If the final argument is a lambda, Kotlin lets you place its braces after the call parentheses.

fun applyTwice(n: Int, operation: (Int) -> Int): Int {
    return operation(operation(n))
}

Inside main:

println(applyTwice(2) { it + 3 })

The first call changes two to five; the second changes five to eight.

A function parameter can be called repeatedly with intermediate results.

challenge icon

Challenge

Medium

Complete twiceDouble with parameters value: Int. Use the supplied applyTwice helper and a doubling lambda. Return the result after applying the doubling operation twice.

Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.

Return a value of type Int. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.

Try it yourself

fun applyTwice(n: Int, operation: (Int) -> Int): Int {
    return operation(operation(n))
}
fun twiceDouble(value: Int): Int {
    // Write your solution here.
    return 0
}
fun main() {
    val value = readln().toInt()
    println(twiceDouble(value))
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Kotlin playground