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

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

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

Kotlin support Lambdas and Higher Order Function(HOF) which was not available into Java (Though added later as Java Streams). Both this feature is very powerful and can make code neat and clean if used properly.

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

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

  1. Basic understanding of Kotlin
  2. Little familiarity with Lambdas
  3. Piece of brain (if needed)

So let’s get our hand dirty with some code


Here’s the line by line explanation of code :

  1. We declared main function which is necessary for kotlin program to start execution.
  2. We declared variable name fibonacciSequence and used generator function to assign sequence value to it. we passed map as parameter (1 to 1)
  3. In Fibonacci series, calculation of 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 special variable available in kotlin if your lambdas have only single input.
  4. We are getting Value of Pair<Int,Int> that is second Int using lambda expression {it.second}.
  5. Theoretically you can create infinite sequence with sequence generator, so we need to take only certain values that we need. Here we taking 20 values from sequence and printing it.

It was just single example of what you can do with lambdas and HOF. Though it can be bit complex for beginners, it will be easy once you understand use of lambdas and Higher Order Function.

That’s all folks. If you like this article, please share this story and follow me on medium.