Skip to main content

Kotlin: Higher order functions, Lambdas and Extension methods

Photo by Aaron Burden
“Truth can only be found in one place: the code.”
―Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

Happy winter, how are you?. This post is continuation of Kotlin series. If you haven't read my introductory post about Kotlin then I'll recommend you reading previous post before continuing with this one.

Kotlin is a modern language. I've been working with kotlin for past few months now and I just love it. In todays post I'll talk about three features of kotlin viz. Higher Order Functions, Lambdas and Extension methods. This post also contains working code showing of each of these features. You are free to copy the code and experiment with it. If you haven't already setup kotlin on your system then you can run code using kotlin online playground.

Higher order functions

Higher order function are gist of modern functional programming languages. They treat functions as first class citizens of language in simple terms, Functions can be assigned to variables, passed to another functions as argument, can be returned from another functions and can be defined without need of wrapping them in top class unlike Java. This simple idea makes whole lot of different between non-functional languages such as Java (prior to version 1.8), C++ std11 and C. It makes code easier to read and safe (functions can be made almost side-effect safe) for threading environments. Let's see an example in kotlin.

Cool eh!, you might be asking Kotlin compiles to Java(ver 1.5 or ver 1.8 depending upon compiler configuration) and Java doesn't support them natively then how it all works under the hood?. Well to start with all the naked functions (functions without wrapper class not clothes) are placed inside a global utility class as static methods. And functions that are returned from another functions or passed as arguments to them are actually wrapped in functors (function+object C++ terminology). Tip: you can always see byte code generated by kotlin compiler which actually is pure Java code with some metadata.

Extension methods

Have you ever experienced the pain of repeating few lines of code again and again to do something that otherwise should have to come with class that came with standard library of language or from third party developer. Often number of lines of code are small enough that makes whole effort of extending the whole class and adding code into it a waste of time or source code of class is not available for you to access it. This happens very often in languages like Java. An old solution for this problem is to add a global method in utility which takes object of the required class as receiver and applies appropriate operation. Or if you are working in Koltin you can use extension methods. Let's first see an example then I'll explain what going on here.

In the code, you can see both approaches implemented, function toDateMethod is how I would've handled the issue in language other than kotlin. I've also included this method to show you the underlying implementation of kotlin extension methods. What kotlin does is that for every extension method it generate methods with signature (receiver, arg...) where receiving object is object over which the extension method is to be applied. Extension method hence is a syntactic sugar hiding the dirty parts beneath. Now let's move on to the last one i.e Lambdas.

Lambdas

Lambdas are like anonymous functions, they have no name, can be assigned to a variable to be used later and can be passed to another functions. If you have little experience with GUI programming then you would already have tasted the pain of writing large boiler plate code task for task as trivial as adding click listener on a button. Lambda comes in handy in these kind of cases. Best example of this is Android Framework(obviously). Google realized the pain of programmers who have to write large amount of unnecessary code in Java (ver 1.5) to get things done and hence they added kotlin support. Let's see an example of Lambdas in action.

In code, I have simply tried simulating a basic scenario of listening for click event from button. Imagine having more than 100 components to listen to for more than 1000 different event. That's hell a lot amount of code. Kotlin's compiler does the dirty job for you while providing elegant and readable syntactic sugar.


Well, that's all for this one. If you encountered errors or have questions regarding kotlin or have accidentally launched a Nuclear Missile (I am serious this time) just comment here and I'll try my best to help you out. Comment if you liked it; Follow if you loved it(show some love naa ❣). Have a nice time.

Comments

Popular posts from this blog

Kotlin Coroutines : A Comprehensive Introduction

Photo by Fleur Treurniet on Unsplash “Redesigning your application to run multithreaded on a multicore machine is a little like learning to swim by jumping into the deep end.” —Herb Sutter, chair of the ISO C++ standards committee, Microsoft® In this article What are coroutines? Blocking vs. Non-Blocking Kotlin Coroutines Suspending functions CoroutineScope Coroutine builders Coroutine dispatcher Coroutine start Conclusion What are coroutines? Coroutines have been around for quite a time now. They are in-fact one of the ideas which helped develop multitasking operating systems. A coroutine in trivial most is a subroutine or function generalisation which in non-preemptive environment (operating system or OS in short) can voluntarily yield the CPU time so that other such sub-routines can use it for themselves without losing the results of previous computations and then can conti

Programmer? A Computer Programmer?

“Programming is like sex. One mistake and you have to support it for the rest of your life.” —Michael Sinz Well, to start with, “A programmer is someone who writes computer code, which tells computer what to do? and how to do it?” . Computing machines are dumb, trust me they are. They have enormous processing power but they don’t have hardware to direct this power to any productive use. And thats exactly where programmer kicks in. Programmers however are not the wizard depicted in the movies. They are humans like me and you. Its just that they think much more rationally than average human does. Types of programmers: The System Programmers: First of all a great tribute to these guys. They are the one who deal with software at the lowest level. They have veteran low level languages (languages which closely resemble with the hardware) —Assembly Language, Machine language in their arsenal. A typical system programmer works closely with hardware engineers bec

Kotlin : An introduction

Photo by wu yi “A language that doesn't affect the way you think about programming is not worth knowing.” ―Alan J. Perlis World was nice and there was only assembly(“real programmers code in assembly”) but then one day out of blue he (hey! don't look at me like that I too don't know his name) came and said let there be compilers and interpreters(line by line) that will translate languages easy to read(uh! nah not really) and write into assembly to make programming fun again and that gave birth to an era of exotic new programming languages called procedural programming languages. Procedural programming languages were doing fine but after some time lot's of programmer started loosing their objects because of stateless functions which globally caused chaos. Seeing all this made him angry. So he said, “Procedural languages, I command you to treat everything as an ‘Object’ which will have it's own properties(attributes) and behavior(methods)”. They respond