Generate Fibonacci series in 6 lines of code with Lambdas in Kotlin

Yes, you read that correctly. With the power of lambdas and higher-order functions, you can generate the Fibonacci series in only 6 lines of code.

Because Kotlin is a JVM language, it runs on the same platform as Java. Although Java is a very popular and wonderful language, many of us may regard it as an old language that is not well suited to modern programming needs. Kotlin enters the picture now. Kotlin is a very powerful and feature-rich programming language that combines the power of Java with its own. It has some great features such as NullPointerException (NPE) avoidance, co-routines, data classes, and so on.

Kotlin supports Lambda and higher-order functions (HOF), which Java does not (Though added later as Java Streams). Both of these features are extremely powerful and, when used correctly, can make code neat and clean.

Lambda expression is simply an anonymous function that takes input and returns output and is represented as an expression using an arrow symbol like x -> x+y. Higher Order Function is a function that can take another function as input and/or return a function as output.

So, let’s get our hands dirty with some code

fun main(arr: Array<String>) {
    //Generating Sequence starting from 1
    val fibonacciSequence = generateSequence(1 to 1) {
        //Calculating Fn  = Fn-1 + Fn-2 and mapping to return Pair<Int,Int>
        it.second to it.first + it.second
    }.map { it.second } //Getting first element of next sequence
    println("First 20 Fibonacci numbers are : 0,1, ${fibonacciSequence.take(20).joinToString()}")
}

Here’s the line-by-line explanation of the code:

  1. We declared the main function which is necessary for the Kotlin program to start execution.
  2. We declared the variable name fibonacciSequence and used the generator function to assign sequence value to it. we passed the map as a parameter (1 to 1)
  3. In the Fibonacci series, the calculation of the next number is done by equation Fn = Fn-1 + Fn-2. So we are calculating it, mapping it like Pair<Int,Int> and returning it (you don’t need to write return). it is a special variable available in Kotlin if your lambdas have only single input.
  4. We are getting the Value of Pair*<Int,Int> that is second Int using lambda expression {it.second}*.
  5. Theoretically, you can create an infinite sequence with a sequence generator, so we need to take only certain values that we need. Here we take 20 values from the sequence and print it.

It was just one example of what lambdas and HOF can be used for. Though it may appear complex at first, it will become simple once you understand the use of lambdas and Higher Order Functions.

Share with your friends

Leave a Reply

Your email address will not be published. Required fields are marked *