This article was originally posted on Medium on December 2017
There’s a saying that “design patterns are workarounds for shortcomings of particular language”. Which would be very interesting, if it wouldn’t come from a Lisp or Scheme advocates around ‘96.
But it seems that Kotlin language designers took this saying really to heart.
Of course, the first design pattern that comes to mind is Singleton. And it’s built right into the language. Behold, object:
From now one
JustSingleton.value will be available from anywhere in the package.
And no, it’s not a static initialization, as one may think. Let’s have something slow happen inside:
It’s initialized lazily on the first call:
Test started Computing Done computing in 5376ms "45f7d567-9b3e-4099-98e6-569ebc26ecdf" Took 5377 ms "45f7d567-9b3e-4099-98e6-569ebc26ecdf" Took 0 ms "45f7d567-9b3e-4099-98e6-569ebc26ecdf" Took 0 ms
Note that if you don’t use it this completes in 0ms, although object is still defined in your code.
Test started Took 0 ms Took 0 ms Took 0 ms
Then comes the Decorator. You know, the one that allows you to add a bit of functionality around some other class. Yeah, IntelliJ would generate them for you. But now it goes even further.
How about we have a HashMap, that gets excited each time a new key is added?
You define a backing instance in the constructor, and delegate all methods using
Note that we can access our own map with square brackets, and have all other methods work as before:
Companion object allows you to easily implement FactoryMethod. The one where you want the object to control how it’s initialized. Probably because it has some secret stuff to do inside.
No one can change SecretiveGirl age now:
Last one for today is Strategy. Since Kotlin has higher order functions, this one is also super easy:
And to change behavior at runtime:
Note that it’s indeed a Strategy pattern, and changing signature won’t work (hi, JS!)
As usual, all the code is available on my GitHub page:
And if you’re interested to learn more about Kotlin and design patterns it brings with it, there’s an excellent “Kotlin in Action” book available. It’s an interesting read, even if you don’t plan to use this language in the near future (although you should).