Menu
Coddy logo textTech

Writing Lambdas

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

A lambda is an expression that creates a function value. Put parameters before -> and the calculation after it. The final expression becomes the result; a lambda can be stored in a variable and called with parentheses.

Inside main:

val triple = { n: Int -> n * 3 }
println(triple(4))

The lambda receives four and returns its last expression, four times three.

A lambda uses its final expression as its result.

challenge icon

Challenge

Medium

Complete applyTriple with parameters number: Int. Define a lambda named triple that multiplies its argument by three. Call it with number and return the result.

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