Kotlin Fun With The Factory Pattern
Tags: kotlin, designpatterns, programming, beginners
Published: 2018-02-25 20:59:14

---
title: "Kotlin Fun With The Factory Pattern"
published: true
tags: kotlin,design-patterns,programming,beginners
canonical_url: https://medium.com/the-coding-matrix/kotlin-fun-with-the-factory-pattern-70aa5e431dba
---

![](https://cdn-images-1.medium.com/max/1024/1*c_5J7SGs24bGbFFjzf8wWw.jpeg)

When you read “let’s have some fun with the factory pattern”, I agree that you should doubt the writer’s enthusiasm and see for yourself. But, as I was writing some code to play with this language I’ve recently fallen in love with, I asked myself, “How should I write a factory method?”

This simple question led me to some experimentations.

### Ok to have some fun, but … what’s a factory?

For those in need of a reminder, the factory is a creational pattern listed in the book commonly referred to as “the GOF”. If you haven’t heard or read about it, there’s still time to catch up. If it falls in the TL;DR category, don’t hesitate to google the world of patterns; there are plenty of resources available on the internet (and Wikipedia is a satisfactory one for a quick introduction).

The factory’s goal is to deliver a ready-to-use object to its client. The factory hides the complexity of creating and selecting the right object for the job.

As we’re all fond of UML, I’ll sketch something that vaguely looks like UML (on a Saturday night) so we’re on the same page.

![](https://cdn-images-1.medium.com/max/601/1*yUDdxb-0B6eGrL9UmIHgRw.png)

### The Factory as it is in the GOF

Now that we all remember what a factory is (I know you knew it — but just in case), let’s write the first candid Kotlin implementation.

Say we have a _product_ called a FileParser that we need so that we can read information from files we would otherwise be oblivious to.

{% gist https://gist.github.com/geraldcroes/091190ed90ea73879a2e34fa4ce20456 %}

And let’s say that we have two available implementations of this FileParser, one dedicated to understanding XML (XmlFileParser) and one dedicated to understanding JSON (JsonFileParser).

{% gist https://gist.github.com/geraldcroes/e35af4bf5f3c8b6641767010d50cb500 %}

So we’re done with our products description.

The client (our program) will need one of the two available implementations. To make the right choice, the logic is to test the filename and test its extension. If it’s “.xml”, use XmlFileParser, if it’s “.json”, use JsonFileParser. To avoid testing this everywhere in the code, we have decided to use the factory pattern that, thanks to its createFromFileName(fileName: String) method, will give us the correct FileParser…

…which is implemented at lightning speed thanks to Kotlin.

{% gist https://gist.github.com/geraldcroes/111cb13f7a9d46ae02c1fd086566a6a6 %}

There we are — we have a to-the-letter implementation of a factory in Kotlin.

If we wanted to use the factory, we’d have written:

{% gist https://gist.github.com/geraldcroes/800ee63517e84b4598d4d9bfbc1b675e %}

### You said it would be fun…

Yes, I know what I said, so let’s keep diving into the subject.

What’s a bit boring with our factory is that we need to instantiate it. It’s not a lot of lines, but still. I’d love to be able to write something like

{% gist https://gist.github.com/geraldcroes/32def76a8a7b2e2c5adb5feb3f6efe86 %}

One line shorter … yes … it’s worth it!

The syntax looks like a static call, but as there is no “static stuff” in Kotlin, we’ll use a different trick — _companion object_. These objects are kinds of _singletons_ attached to the class (see [companion objects in the documentation](https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects)).

{% gist https://gist.github.com/geraldcroes/226ad1f93cdbe6f6d97d0262ce3a43c0 %}

Now we can use the previous syntax, and it’ll work. But the caveat is that we can no longer call the createFromFileName method from an instance of our FileParserFactory, only from the class itself with a static-like call.

And if you carefully read the code, you’ll see that our class doesn’t implement FileParserFactory, our _companion object_ does.

Of course, we could write a sort of synonym for our instance to be able to expose such a method, but that would be ruining the concept. See for yourself:

{% gist https://gist.github.com/geraldcroes/4b8d56094634f0658cecf25384740a90 %}

If you’re asking yourself, “What’s wrong with having the static syntax as your only option?” I’ll answer with the simple, “It’s wrong because you can’t pass an instance of your factory to another object. Every client of the factory will have to be hardwired to the implementation of your CompanionObjectFactory.”

### So … are we having fun yet? Just asking.

Er … Ok, let’s try another syntax.

If we still want to save a line of code while creating our FileParser, we can use another Kotlin feature, which is the _object_ keyword. The object keyword is a way of asking your code to ensure that only one instance of a class will be available at any time in the life cycle of your application.

Let’s see how it’s done.

{% gist https://gist.github.com/geraldcroes/aa1d4493c1e66d042c81428e87de67b6 %}

Yes, we’ve just replaced the _class_ keyword by the _object_ keyword.

From now on, we can use the one line option along with the possibility of calling the method from the instance itself.

{% gist https://gist.github.com/geraldcroes/e2b8d6009f2a7e24a29feeaf09436747 %}

I’m thrilled, my head is spinning right now…

Man you’re tough. Let’s try to spice things up then.

So, we have these FileParserFactories that handle the creation of FileParsers. That’s nice, but it would be nicer if we could embed the factory within the FileParser interface itself. Good news: in Kotlin, we can add a _companion object_ to an interface.

{% gist https://gist.github.com/geraldcroes/6ffa82303b3f04850321e3c8467c9e64 %}

Isn’t that fun? (At least for someone who comes from Java.)

{% gist https://gist.github.com/geraldcroes/40e34cb2e92651eb3ef6fd11ee5089e2 %}

Once again, we cannot give the factory instance to another object, but … is it still needed as the interface itself embeds its own factory? I agree that this very question is open to debate (because I do not fully agree with myself right now — I’m just getting carried away with the Kotlin syntax).

### But if I need a different factory? How can I…

Hey! Excellent question.

The super fun thing with Kotlin is that you can add extensions to existing code. So if you need to write your specific factory, you can add it like this:

{% gist https://gist.github.com/geraldcroes/4723c34f4021ef146919112d732d2c3c %}

Yes, you’re “adding” a new method to the _companion object_ within the interface, so from now on you will be able to call the new _factory_ (fromFile) you’ve just declared.

### More fun with a fun syntax

Imagine that you could write

{% gist https://gist.github.com/geraldcroes/42982ced2f907fdfce5c434796c00315 %}

Well, actually you can, by adding the keyword infix before your extension :-)

{% gist https://gist.github.com/geraldcroes/88179fe2d4e42f0c5997998dd3d18728 %}

Infix means that you don’t need to call the method using the traditional syntax, you can call it the fancy way.

### Well yeah … why not a factory method in the String itself?

You don’t say! Let’s do this :-)

{% gist https://gist.github.com/geraldcroes/66c5a5523b7a8c21d557253f292a3410 %}

So we can now create a FileParser using this syntax

{% gist https://gist.github.com/geraldcroes/1e6224dc36d6f45cab9b9ba07cb0bfe5 %}

### That’s all the fun you’ll get for now

I’m sure there are many other ways to write crazy factories in Kotlin, but I was happy to share these ideas as I played with the language. If you want to tinker with the examples, you’ll find them in [this GitHub repository](https://github.com/geraldcroes/kotlin_design_patterns).

Don’t hesitate to share your ideas (or your rants, as you wish!) in the comments.

* * *