Power of Kotlin : Generate Fibonacci series in 6 lines of code with Lambdas and Higher Order…

Power of Kotlin : Generate Fibonacci series in 6 lines of code with Lambdas and Higher Order…

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

Kotlin is a JVM language, which means it runs on the same platform used by Java. Although Java is a very popular and great language, many of us may consider it an old language that is not so suitable for modern programming requirements. Here comes Kotlin into the picture. Kotlin is a very powerful and feature-rich language having combined power of java and its own. It provides some great features including Avoidance of NullPointerException(NPE), Co-routines, Data classes etc.

Kotlin supports Lambda and higher-order function (HOF) which is not available in Java (Though added later as Java Streams). Both these features are very powerful and can make code neat and clean if used properly.

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.

Before we start, here are the basic requirements to understand this article better.

  1. Basic understanding of Kotlin

  2. A little familiarity with Lambdas

  3. Piece of the brain

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 a single example of what you can do with lambdas and HOF. Though it can be a bit complex for beginners, it will be easy once you understand the use of lambdas and Higher Order Function.

If you enjoyed this article, consider following me.