CodeBlanks Logo Icon CodeBlanks

Summary - Functional programming

Combine immutability, Sequence and Result to write a functional pipeline.

Summary - Functional programming

In this group you saw the core of functional programming: immutability with data class, pure functions, laziness with Sequence, accumulation with fold and the monad approach with Result.

This lesson includes a small task that combines three of them: you will define a data class and compute a total with fold. This pattern is the foundation of functional Kotlin.

Practice Summary: Product and fold

Define a data class Product(val name: String, val price: Int). In main create a list of three products, compute the total price with fold(0) { acc, p -> acc + p.price } and print it with println.

Starter code

Main.kt
// Product data class: name and price properties
// in main list three products, compute total with fold

Sample solution

Main.kt
data class Product(val name: String, val price: Int)

fun main() {
    val items = listOf(
        Product("Bread", 20),
        Product("Milk", 15),
        Product("Tea", 25)
    )
    val total = items.fold(0) { acc, p -> acc + p.price }
    println(total)
}

Expected output

60

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a core feature of functional programming?

  • Immutable data Correct answer
  • Lots of side effects
  • Frequent global state mutation
  • Loops everywhere

Explanation: Immutability is core to functional programming.

2 Match the FP concepts

Term Meaning
data class Immutability
fun double(n) Pure function
asSequence() Laziness
fold(0) Accumulation

3 Complete the fold call

Question
val total = items.____(0) { acc, item -> acc + item.price }
Answer
val total = items.fold(0) { acc, item -> acc + item.price }

Explanation: fold accumulates with an initial value.

All lessons in Advanced