Member-only story

Embracing the Magic of Functional Programming in Kotlin

PINAR TURGUT
5 min readNov 13, 2023

--

Hey there👋 Today, let’s dive into the enchanting world of functional programming and how we can sprinkle a bit of its magic into our everyday Kotlin coding adventures.

🌟Traditional Approach: Step-by-Step Procedures

In traditional, imperative programming, we often approach problem-solving by breaking down a task into a series of step-by-step procedures. It’s like giving a set of instructions to a computer, one after the other. For example:

// Imperative approach
fun calculateTotalPrice(items: List<Item>): Double {
var totalPrice = 0.0

for (item in items) {
totalPrice += item.price
}

return totalPrice
}

🌈Functional Approach: Transformations and Computations

Now, let’s shift to a functional mindset. Instead of thinking about procedures, think about transformations and computations. Functional programming encourages expressing what you want to achieve rather than detailing how to achieve it. Here’s how the previous example might look functionally:

// Functional approach
fun calculateTotalPrice(items: List<Item>): Double {
return items.sumByDouble { it.price }
}

In this functional approach, we’re expressing the transformation we want: calculate the total price of items. We’re leveraging the sumByDouble function, which internally handles the iteration and accumulation. It's more about what we want to achieve rather than how to achieve it step by step.

✨✨✨Functional programming Principles✨✨✨

1. Immutability:

Data in functional programming is immutable, meaning once a piece of data is created, it cannot be changed.

--

--

PINAR TURGUT
PINAR TURGUT

Written by PINAR TURGUT

Android developers who is passionate about personal growth https://pinartechtips.com

Responses (1)

Write a response