Functional programming
This section aims to consolidate your understanding of functional programming and when you should use it.
Functional programming is based on the following features:
- Pure functions
- First-class functions
- Higher-order functions
- Function composition
- Typeclasses
- Lambdas
- Closures
- Immutability
Contrary to object-oriented languages, which are written in an imperative style, functional programming languages are written in a declarative style.
Declarative versus imperative
With functional programming, you can write code that allows you to concentrate on business logic instead of specific implementations. The following example is written in an imperative style:
val numbers = listOf(1, 2, 3, 4, 5, 6, 7) val odds = ArrayList<Int>() for (i in 0..numbers.lastIndex) { val item = numbers[i] if (item % 2 != 0) { odds.add(item) } }
If we rewrite this code in a declarative style, it will look as follows:
val numbers = listOf(1, 2, 3, 4, 5, 6, 7) val odds = numbers.filter { it % 2 != 0 }
This...