Tag Archives: Kotlin

Refactoring to Functional–Why Class?

This is a multi-part series on Refactoring to Functional Programming

  1. Getting Started
  2. Basic Primitives
  3. Reducing and Flattening Lists
  4. Why Class?

In College

Teacher: We are surrounded by objects in the real world. These can be cars, houses, etc. That’s why it’s very easy to associate real world objects with classes in Object Oriented Programming.

2 weeks later

Jake: I’m having a bit of hard time with these objects. Can you give me some guidance?

Teacher: Sure. There’s actually a couple of more or less formal processes to help you, but to sum it up, look for nouns. And verbs are like methods that can be performed on the class. The behavior so to speak.

Jake: Well that seems reasonable. Thanks!

Jake graduates.

Jake’s on the job

Phil: Hey Jake. I’ve been looking at this class of yours. It’s a little bit too big.

Jake: Sorry. And what’s the issue with that?

Phil: Well, thing is. It’s got too many responsibilities. It does too much.

Jake: And?

Phil: Well think about it. If it does too much, it means that it touches many parts of the system. So the probability of having to touch the class when changing code is higher, which means more probability of breaking things. Plus, 1000 lines of code in a single class is harder to understand than 30 lines.

Jake: Yeah. Makes sense.

Phil: Break these up into smaller classes. That way each class does only one thing and one thing alone.

A year later

Mary: Jake, I’m just reviewing this class of yours, there’s not much behavior in it.

Jake: Yeah well I wasn’t sure if that behavior belonged in the Customer class or to the Accounts class, so I placed it in this other class called CustomerService.

Mary: OK. Fair enough. But the Customer class isn’t really a class anymore. It’s more a DTO.

Jake: DTO?

Mary: Yes, a Data Transfer Object. It’s like a class but without behavior.

Jake: So like a structure? A record?

Mary: Yes. Kind of. So just make sure your classes have behavior. Otherwise, they’re not really classes. They’re DTO’s.

Jake: OK.

2 years later

Mathew: Jake, looking at this class. It’s tightly coupled to a specific implementation.

Jake: Huh?

Mathew: Well, you’re creating an instance of Repository inside the Controller. How you going to test it?

Jake: Hmm. Fire up a demo database?

Mathew: No. What you need to do is first off, program to an interface not a class. That way you don’t depend on a specific implementation. Then, you need to use Dependency Injection to pass in a specific implementation, so that when you want to change the implementation you can.

Jake: Makes sense.

Mathew: And in production, you can use an IoC Container to wire up all instances of the different classes.

3 years later

Francis: Jake. You’re passing in too many dependencies into this class.

Jake: Yeah but the IoC Container handles that.

Francis: Yes. I know but just because it does, it doesn’t make it right. Your class is still tightly coupled to too many other classes (even though the implementations can vary). Try and keep it to 1 to 3 maximum.

Jake: OK. Makes sense. Thanks.

4 years later

Anna: Jake. This class, why did you name it Utils?

Jake: Well. I didn’t really know where to place that stuff cause I don’t know where it really belongs.

Anna: OK. It’s just that we already have a class for that. It’s called RandomStuff

Over a beer…

Jake: You know Pete, I’ve been thinking. They teach us that we need to think in terms of objects and identify these with nouns among other techniques. We then need to make sure that we name them correctly, that they’re small, that they only have a single responsibility and that they can’t have too many dependencies injected into them. And now they’re telling us that we should try and not maintain state because it’s bad for concurrency. I’m beginning to wonder, why the hell have classes at all?

Pete: Don’t be silly Jake. Where else are you going to put functions if you don’t have classes?

Pete: Another beer?

Until next time.

Kotlin and ReSharper in Australia

I’ll be in Australia soon for YOW! Conference, where in addition to giving a talk I’ll be giving a workshop on Refactoring and dealing with legacy code with ReSharper, both in Melbourne and Sydney. There’s still time to sign-up!

In addition, the folks of the Melbourne JUG and Sydney JUG have been kind enough to host me to give a talk on Kotlin. We’ll be putting Kotlin to the test and I hope to be able to answer any questions you might have, so it will be as interactive as possible.

Finally I’ll also be at DDD Brisbane where I’ll be giving a talk and a Q&A Panel.

Hope to catch you at one of the events. And once again, thanks to YOW organizers for making this all possible.

Refactoring to Functional– Reducing and Flattening Lists

This is a multi-part series on Refactoring to Functional Programming

  1. Getting Started
  2. Basic Primitives
  3. Reducing and Flattening Lists
  4. Why Class?

In this part let’s pick up some more primitives of functional programming and see how we can use them. We’re going to expand the previous list of albums to also include track information

We’re going to solve two different exercises this time:

  1. Get a list of albums and their total duration.
  2. Get a list of tracks that are shorter than a certain length, along with the corresponding album title.

To get a list of albums and their total duration, we’ll go for the simplest approach, using some of the primitives we picked up in the previous part.

reducing to a single value

What we’re doing in the previous code is iterating through the list of tracks and summing them up. As expected, there’s a function for that: reduce. Reduce takes a list of items and returns a single value, applying a specific operation to the list.

Knowing this, we can refactor the code to use reduce.

reduce versus fold

Kotlin also provides a very commonly used function named fold which does the same thing as reduce. The difference between the two is that fold takes an explicit initial value, whereas reduce  uses the first element from the list as the initial value.

Dealing with trees

Up to now, we’ve used forEach, map, filter and reduce to perform operations on lists. The problem with trying to find a list of tracks that meet a certain criteria is that this list is a list inside another list, i.e. we have a tree, albeit a small one. Filtering the original list is not going to work since the information to filter is on a branch. We therefore need to filter out based on the branch.

Here’s a first attempt

What we’re doing is iterating through the list of albums, and then for each one, filtering out those that match a certain criteria. On each iteration we hold a reference using a closure to the current album, and then add those matching the criteria as a new pair to the result.

Once again we can avoid some of this manual work and delegate it to a function named flatMap that takes a list, applies a transformation to each item and returns a new list with these items.

With that, we can refactor the previous code to

There’s a more generic version of flatMap, named flatMapTo which allows us to specify the resulting collection.

Other constructs as they come

In addition to filtering results, we can also find out if an item on the list matches a certain predicate with any, or if all items match it with all and last but not least find the first item that matches it with find.

We can also group items of a list or zip two lists (combine items from each list into pairs into a new list) as well as perform a few more basic operations on lists. Hopefully with these constructs we’ll have enough to solve problems.

Until next time.

Refactoring to Functional– Basic Primitives

This is a multi-part series on Refactoring to Functional Programming

  1. Getting Started
  2. Basic Primitives
  3. Reducing and Flattening Lists
  4. Why Class?

Say we have a list of great albums (i.e. Pink Floyd’s discography*)

We want to get a list of all albums that were number one in both the US and the UK.

The Imperative Approach

Let’s go for the simple approach. A for loop iterating the length of the list and adding the new items to another list.

This works and is simple enough. But there are a couple of issues, if we’re trying to abide by the functional paradigms highlighted in the previous post. In particular, treating things as infinite. Here we’re consciously aware of the length of the list.

Refactoring to infinite lists

We want to avoid having to deal with indices, lengths and counts and worrying whether we have some element in or out of bounds. So the first step is to refactor to remove the actual loop index. In Kotlin, there is a for in loop which allows us to iterate through anything that has an iterator() function. In other words, anything that implements Iterable<T>.

Now we no longer need to deal with lengths.

Adding some syntactic sugar

The previous is better, but we can add some syntactic sugar. Instead of explicitly having a for in we can use an extension function that Kotlin provides, forEach which does the same thing

Since we no longer have the actual album element we can reference the current item the iterator is on using the it reserved word in Kotlin.

What we want instead of how we want it

If we look at the previous code, what we’re doing is removing elements that don’t match a certain criteria. We’re doing this by creating another list and adding the ones that do match to this new list. But if we were to remove the name of the function, to understand what we’ve just described, we’d need to mentally envision it taking into account the for loop, the temporary list, etc.

Of course, with this code it isn’t that hard but add another embedded for loop and things can start to get ugly.

The problem here is that we’re telling the computer how we want something done, instead of what we want done. What we want is to filter a list. What we’ve done is create another list and copy items to it, then return that list. Why not instead just filter the list?

Refactoring to asking versus telling

In Kotlin there is a filter function that takes a list and returns a new one that matches a certain predicate.

We can therefore refactor the code to

The reason we’re omitting the parenthesis is that by convention in Kotlin, if the last parameter to a function is another function, we can omit these.

As a side-effect of this refactoring, we’ve also removed the temporary list, and while in the previous code, hits was declared as immutable, the list itself (declared as ArrayList) was mutable. Win?

Changing data types

What happens now if we need something slightly different? We’re not always bound to work with the same type of data. Let’s assume for instance we want to return the years where an album made it to number one in both the UK and the US. We could of course do the following

The problem is that we re-introduce again some of the issues we had previous, namely using a temporary variable and again telling the computer how we want something versus what we want.

Using Map to transform results

Much like filter, Kotlin offers another function to help us do this: map.

which takes a function that given an input of type T produces an output of type R, returning a list of R. We can therefore refactor the previous code to

Once again we’ve gone from saying how to do something to asking for it.

Basic Primitives

The two functions we’ve just used: map and filter are some of the main primitives in functional programming. With them we can start to treat lists as infinite, chain them and transform results to what we need without having to deal with for loops, lengths, indices or complicated loops. We’ll see if they actually do help dramatically as we start working on more complex scenarios.

Until next time.

*The true Pink Floyd.

Writing Kotlin in the Browser

Did you know that Kotlin can target JavaScript as well as the JVM? Don’t be too surprised if you didn’t know, as we’ve not been giving it too much coverage, despite already shipping a successful product that uses this capability. But here’s hoping to change things.

The Basics – A Simple Project

First step is to set up a new project. When using Kotlin in a project, we have the ability to target either the JVM or JavaScript. If we’re adding a new Kotlin file to an existing project, Kotlin will prompt us for this. If we’re starting a new project, we can choose the target during the setup wizard, assuming we’re using IntelliJ IDEA.


We also need to add the Kotlin standard library to the project. Clicking on the Create button we’ll be prompted with the location where we want these files copied. By default it copies is to a folder named script. And we’ll get to this later on as it’s important.


Project organization

The resulting structure of the project should be


The project has two files that are added:

  • The lib folder contains the header files, as a jar file, which are used during development.
  • The script folder contains a single kotlin.js which is the Kotlin runtime library. This is used in production.

All our Kotlin source code should be placed in the src folder. Once this is compiled, it will generate some JavaScript files that need to then be shipped along with the kotlin.js runtime file.

All other source code, be this external JavaScript libraries or files, CSS and HTML files can be placed anywhere, preferably in the same project to make development easier but not necessarily. For our example we’re going to place this in a folder called web and create a series of subfolders to structure our code.


Setting up a workflow

When we write Kotlin code,the compiler will generate some JavaScript which needs to be shipped as part of our application. By default, IntelliJ IDEA will output this file and its sourcemap to a folder named out/production/{project_name}


During development we need to have an up to date version of these files so ideally we’d like to have these located in our web/js/app folder. We can do this in many ways, either using IntelliJ IDEA artifacts or Maven/Gradle. In our case we’re just going to use an artifact. We can set one up to copy the corresponding files to the desired output location and additional also copy the kotlin.js file that was originally copied to the script folder to the same location*.

*This is a one-time operation so a better alternative is to define the output location of this file directly to our required output folder when setting up the project. We have done it this way to explain things step by step.

Interacting with DOM Elements

Now that we have the project layout ready, let’s start writing some code. The most basic thing we can do is manipulate some DOM elements. We can create a simple HTML page (named index.html) and place it under the web folder

The idea is to now update the value of the input field using Kotlin.  For that we can create a new file called main.kt and place it under our src folder.

Web-targeted Libraries

Kotlin provides a series of libraries targeted specifically at the web. In our case, since we want to manipulate the DOM, we can import the js.dom.html to access the documentvariable. The resulting code would be

which is very straightforward. We’re using the document.getElementById to retrieve the DOM element and then setting its value using setAttribute. Exactly the same way we’d do it using JavaScript, except here we’re using Kotlin and have the benefit of static typing, among other things.

The standard library already provides support for DOM manipulation, HTML 5 features such as Canvas and Local Storage, as well as wrappers for common libraries such as jQuery. We will be adding more as we go along, and we’ll cover some of them in future posts.

Running the code

Now that we have the code compiled, we need to actually run it. For this we have to reference both the kotlin.js as well as the generated (basic.js) file from our index.html page.

The code corresponding to the main function will automatically be called when the page is loaded.

Once we load our index.html page, we should see the result.


Calling Kotlin from JavaScript

What if we have for instance some code in Kotlin we want to use from JavaScript? For instance, think of scenarios where you need to do some sort of business logic that needs to be repeated both on the client and the server. Well all we need to do is write it and then call it. Here is a simple function written in Kotlin

This is placed inside the same module as the application and we can call it referencing it by the Kotlin module name*

*This API is not final and will most likely change in the future, and probably will be much more compact.

Next Steps

That’s not all that is possible with Kotlin. One thing we haven’t mentioned is the ability to call JavaScript code from within Kotlin and that is something we’ll be covering in a another post, as this one has already become too long!

If you want to play with Kotlin to JavaScript without having to install anything, you can also try it directly in the browser. And as always, give us your feedback!

Refactoring to Functional–Getting Started

This is a multi-part series on Refactoring to Functional Programming

  1. Getting Started
  2. Basic Primitives
  3. Reducing and Flattening Lists
  4. Why Class?

It’s high-time I improve my functional programming skills, and like my fellow countryman*, I’ll do it in the open. Different to Rob though, I’m going to use Kotlin, not Clojure. Reasons are:

  • I’m loving the language and am mostly comfortable with it.
  • I feel it’s a good stepping stone as it provides familiarity, allowing me to focus on functional paradigms.
  • Kotlin claims to have functional aspects. I’m hoping to prove this right.
  • It fits in nicely with my job.

and most importantly, because I want to.

In a series of posts, I’ll try and look at ways of solving problems using a functional approach as opposed to an imperative one. I’m not a big fan of blog post series, primarily because they require some sort of structure and planning, but this is an ongoing process and I’m not going to wait till the end to write about it. And while a certain level of structure will go into these posts, I can’t commit to how it will pan out so we’ll just pretend it’s not a series.

I want to give up-front credit to @jhusain as some of the ideas and exercises will be based on his LearnRX project as well as my friend Rob whose brain I pick, and will continue to pick with my functional insecurities. Last but not least also thanks to Andrey, who’ll undoubtedly (he doesn’t know yet) will end up doing some reviews.

Functional Programming

Wikipedia defines Functional Programming as

In computer science, functional programming is a programming paradigm, a style of building the structure and elements of computer programs, that treats computation as the evaluation of mathematical functions and avoids state and mutable data. Functional programming emphasizes functions that produce results that depend only on their inputs and not on the program state – i.e. pure mathematical functions. It is a declarative programming paradigm, which means programming is done with expressions.

The key ideas to keep in mind when doing functional programming are:

  1. Everything is a function
    As such we need to stop thinking about objects, classes, etc. other than for returning data or interop with the platform.
  2. Functions should be pure
    A pure function should always return the same output given the same input and should not depend on anything that is not directly the input (i.e. external data). It should also not cause any side-effects.
  3. We shouldn’t maintain state
    Shared state is the root of all evil. Or so they say. In any case, if we can’t really depend on state according to point 2, then why maintain it.
  4. We should consider input infinite
    Apparently it’s better, specially if we combine it with lazy evaluation. We’ll see the benefits at some point. Or at least I hope we do.

Benefits of Functional Programming

Seems there are many benefits to functional programming, including the ability to achieve concurrency more easily as state is not maintained, writing more concise code, and solving some problems which using OO paradigms might not be so straightforward.

But that’s what they say. I want to find out for myself. So until then, I’m going to take it all with a pinch of salt. Worse that can happen is that I end up looking at approaching problems in a different way, and that for me, is definitely a win.

We’ll see…

Kotlin as a functional language

Although Kotlin is far from being a purely functional language, it does have support for functions as first-class citizens and also allows for creating immutable data, so in principle it should suit our needs. If you’re coming from a Java or C# background, you’ll have little trouble getting used to Kotlin’s syntax. I already covered the basics of Kotlin in a four part series and while there have been some changes to the language, much of it remains the same. If you want to follow this series, you can use any flavor of IntelliJ or use the command line compiler with your favorite editor. But for heavens sake, if you choose the latter, let me not catch you using cursor keys.

Top-Level Functions

In Kotlin you can have a file and in the file declare any number of functions, much like you can with JavaScript. There’s no need for a static class or object. We can simply do something like

This function sits standalone, declared as part of a package, and can be used anywhere where the corresponding package is imported.

Immutable Data and Common Data Structures

Kotlin has shorthand for declaring properties on a class, be it a regular class or a data class (i.e. a DTO). When declaring properties we can either make them mutable (var) or immutable (val). To declare a data class with three immutable properties we could do

In addition to creating immutable data types, functional languages such as Clojure use a series of common well-known data structures, namely vectors, lists and maps, all of which are available in Kotlin and we’ll be using.

Until next time.

* I was born in Iran, raised in the UK till I was 10, and living in Spain ever since. Rob as far as I know was born and raised in the UK Isle of Man. Yet I feel a bond. Maybe it’s the Stilton cheese.

Creating Builders in Kotlin– The Results of the Kotlin Workshop

At the beginning of May, I held a Kotlin workshop at Skills Matter in London. The attendees had to go through a series of exercises to get familiar with Kotlin’s language constructs and then do two larger exercises.


Seeing that one of Kotlin’s benefits is the ability to design nice DSL’s, I proposed that they write a JSON Builder and a Build System (i.e. the next Ant, MSBuild, Rake,…take your pick).

We divided up into groups of three people per team and each went off their own way to design their own DSL’s.

Most managed to finish both exercises, or at least finish one and start the second. We were meant to vote on the winning DSL and they’d then get a prize (namely each member of the team would get to choose a license of one of our IDE’s). Unfortunately, 30 minutes prior to ending the class, some had to leave and then I mistakenly mentioned that Beers were happening in the Slaughtered Lamb and all hell broke lose. Moral of the story: we didn’t vote.

But I’m going to keep my word. I’ve managed to collect the outcome of the different teams (or what they managed to complete). I’ve presented them below (anonymously) and leave you all to vote for which one you like the best. The winning team will then receive their prize.

Exercise JSON Builder: Create a DSL to express JSON in Kotlin and output the result to actual JSON.

Exercise BUILD Builder: Create a DSL to define Build Scripts in Kotlin

(Teams are randomly ordered and might not have resemblance with actual seating during the workshop)

Team 1 – Finished the JSON Builder


Team 2 – Finished the BUILD System


Team 3 – Finished the JSON Builder and the BUILD System



Team 4 – Finished the JSON Builder and the Build System




Team 5 – Have not received any entries unfortunately.



Realizing that some participants have submitted both, others only one, and a couple none, just vote for whatever you like the most, be it the JSON Builder or Build system.

Voting will end Thursday 6th of June at 12 pm CET.


Results are in:

Winning Team, with 44% of the votes is Team 3. Close in second with 39% of the votes is Team 1.

Congrats to Team 3. Your licenses will be on the way (contact me if you’re one of the team members).


Thank you

I’d like to extend a thank you to all the participants for having taken part and a big shout out to Skills Matters for facilitating this workshop. You’re doing great things for the community.