Declarative and imperative styles

We used to use the imperative style of programming when writing object-oriented programming, but for functional programming, a more natural style is declarative. The declarative style assumes that our code describes what to do, instead of how to do it, as is usual with imperative programming.

The following example demonstrates how functional programming can be useful in certain cases. Let's imagine that we have a list of numbers, and we want to find the number that is greater than 4. In the imperative style, this may look as follows:

fun imperative() {
val numbers = listOf(1, 4, 6, 2, 9)
for (i in 0 until numbers.lastIndex) {
if (numbers[i] > 4) {
println(numbers)
}
}
}

As you can see, we have to use a lot of control flow statements to implement this simple logic. In the declarative style, it may look as follows:

fun declarative() {
println(listOf(1, 4, 6, 2, 9).find { it > 4 })
}

The preceding snippet demonstrates the power of functional programming. This code looks concise and readable. The Kotlin standard library contains a lot of extension functions that extend the functionality of the list type.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.67.5