Menu
Coddy logo textTech

Captured Variables

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

A lambda can use variables from its surrounding scope. This is called capture. If a captured var changes, a later invocation sees its current value. Captures also let a returned lambda retain state between calls.

Inside main:

var offset = 2
val addOffset = { n: Int -> n + offset }
offset = 5
println(addOffset(3))

The lambda reads the current offset of five when it is called.

A captured mutable variable is shared state, not a frozen copy of its original value.

challenge icon

Challenge

Medium

Complete capturedOffset with parameters value: Int, offset: Int. Create a lambda that adds the surrounding offset to its integer argument, then apply it to value.

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 capturedOffset(value: Int, offset: Int): Int {
    // Write your solution here.
    return 0
}
fun main() {
    val value = readln().toInt()
    val offset = readln().toInt()
    println(capturedOffset(value, offset))
}
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